tags:

views:

35

answers:

2

I have a loop that creates a datastring for an ajax call. Here is the code:

    $(':input','#texes-test-entry-0').not(':button, :submit, :reset, :hidden').each(function(){
        varStr = $(this).attr("id").split('-');
        dataString = dataString + '&' + varStr[1] + '=' + $(this).val();
    });

For all of the text inputs $(this).val() gets me the value that I need, but for the select inputs, I don't need the text value but the selected option value.

How do I catch the the select inputs and treat them differently?

Thanks

A: 

Try putting an if inside the loop that selects all inputs and check if the current element has option, if yes don't process it.

if($(this).has('option'))
{
<ignore>
}
else
{
<process>
}
Sidharth Panwar
That still returns both select and text inputs. Any other ideas?
resonantmedia
How can a text input qualify the if???!!!
Sidharth Panwar
A: 

You don't need to treat select elements differently, the val method will get the selected value from the select.

Example:

<script type="text/javascript">
$(function(){
  var data = [];
  $(':input','#texes-test-entry-0').not(':button, :submit, :reset, :hidden').each(function(){
    varStr = $(this).attr("id").split('-');
    data.push(varStr[1] + '=' + $(this).val().replace(/%/g,'%37').replace(/&/g,'%38'));
  });
  var dataString = data.join('&');
  alert(dataString);
});
</script>

<form id="texes-test-entry-0">
  <input type="text" id="x-id1" value="as%&df" />
  <select id="x-id2">
    <option value="1">one</option>
    <option value="2" selected="selected">two</option>
    <option value="3">three</option>
  </select>
</form>

Output:

id1=as%37%38df&id2=2
Guffa
I figured this out. I had something else wrong. :-) On another note could you explain the reason for two things: 1. Why are you using the push and join methods instead of just creating the string. 2. Why did you use the two replace methods. I am trying to learn here, so if the answers are obvious, please humor me.
resonantmedia
Guffa
Thanks so much.
resonantmedia