Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.each function skips hidden element and using multiple selectors in onchange funtion

Tags:

html

jquery

    $('#step1 input').change(function(){
       $('#step1 input').each(function(){
          console.log($(this).val());
       });
    });
    
    $('#step2 input').change(function(){
       console.log($(this).val());
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="step1">
       Father's Details: &nbsp&nbsp&nbsp
       <input name="hiddenelement" type="text" hidden="hidden" value="This is Father's name" />
       <input name="First Name" type="text" placeholder="Enter First Name" />
    </div>
    <div id="step2">
       Mother's Details: &nbsp&nbsp&nbsp
       <input name="First Name" type="text" placeholder="Enter First Name" />
    </div>

I have the following HTML:

<div id="step1">
   Father's Details: &nbsp&nbsp&nbsp
   <input name="hiddenelement" type="text" hidden="hidden" value="This is Father's name" />
   <input name="First Name" type="text" placeholder="Enter First Name" />
</div>
<div id="step2">
   Mother's Details: &nbsp&nbsp&nbsp
   <input name="First Name" type="text" placeholder="Enter First Name" />
</div>

Using jquery I'm trying to get the name of both father and mother by the following code:

$('#step1 input').change(function(){
   $('#step1 input').each(function(){
      console.log($(this).val());
   });
});

$('#step2 input').change(function(){
   console.log($(this).val());
});

But when I give input as: Father's name as Father and Mother's name as Mother, I get the output as:

Father
Father
Mother
Mother

I have two doubts here. First, why is hidden element skipped and Second, why does changing one div reflect in giving output for both divs. Can I please know where I am going wrong. Would be of great help Thanks in advance.

like image 552
Yash Parekh Avatar asked Nov 07 '22 17:11

Yash Parekh


1 Answers

$('#step1 input').change(function(){
   $('#step1 input').each(function(){
      console.log($(this).val());
   });
});

$('#step2 input').change(function(){
   console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="step1">
   Father's Details: &nbsp&nbsp&nbsp
   <input name="hiddenelement" type="text" hidden="hidden" value="This is Father's name" />
   <input name="First Name" type="text" placeholder="Enter First Name" />
</div>
<div id="step2">
   Mother's Details: &nbsp&nbsp&nbsp
   <input name="First Name" type="text" placeholder="Enter First Name" />
</div>
like image 155
Koby Douek Avatar answered Nov 15 '22 06:11

Koby Douek