开发者

Finding all select inputs with in a loop using jQuery

开发者 https://www.devze.com 2023-01-15 23:51 出处:网络
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(){

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 val开发者_运维知识库ue.

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

Thanks


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


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>
}
0

精彩评论

暂无评论...
验证码 换一张
取 消