Closest find a class and change the input value

Viewed 123

I have added the hidden field in the form and inserting the data into the database. I have 16 fields on my page and If the user enters any value in the field then I have to change the value from 0 to 1 in the input field.

I tried the below code but it's not working.

$(document).ready(function() {
  //Check this link 
  $(".onchangefield").change(function() {

    var val = $(this).closest(".onchangefield").find(".haschange").val(1);
    //$(".haschange").val(1);
    alert(val);

  });
});
<form action="process.php" name="employee" method="post">

  <input type="text" name="name" class="onchangefield">
  <input type="hidden" name="haschange[name]" class="haschange" value="0" />


  <input type="email" name="email" class="onchangefield">
  <input type="hidden" name="haschange[email]" class="haschange" value="0" />


  <button type="submit" name="save">Save</button>
  <button type="submit" name="send_for_approval">Send to approval</button>
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

How to change the value in the foreach.

<?php 
        $i=1;
        $arrayName = array('1','2','3');
        foreach ($arrayName as $key => $value) {?>
             <input type="file" name="slider[]"  class="fileupload onchangefield">
             <input type="hidden" name="haschange[slider][<?php echo $i;?>]" class="haschange" value="">

<?php $i++; } ?>
1 Answers

You can use .next() to get the reference of next input and change value there .

Demo Code :

$(".onchangefield").change(function() {
  var selector = $(this).next() //get next input..
  selector.val($(this).val() != "" ? 1 : 0) //depending on value change value of next
});
<form action="process.php" name="employee" method="post">

  <input type="text" name="name" class="onchangefield">
  <input type="text" name="haschange[name]" class="haschange" value="0" />


  <input type="email" name="email" class="onchangefield">
  <input type="text" name="haschange[email]" class="haschange" value="0" />


  <button type="submit" name="save">Save</button>
  <button type="submit" name="send_for_approval">Send to approval</button>
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Related