Search code examples
jquerystringcontainssetvalue

Set Inputfields Values with Jquery if Text contains String


I am trying to validate an input text field with jquery. If the text field contain a value like "24004" or "24005", then other text fields should be changed

<input list="listname" id="textinput" name="textinput" type="text" value="" required />
<datalist id="listname">
    <option value="24004 - Name1 - Street1 - Place1">
    <option value="24005 - Name2 - Street2 - Place2">
</datalist>

<input id="textinput2" name="textinput2" type="text" value="" required />

<script>
$( "#textinput" )
  .keyup(function() {
    var value = $( this ).val();
    if (value *= "24004") {
        $('#textinput2').val("My new value");
    }
    if (value *= "24005") {
        $('#textinput2').val("My new value");
    }
  })
  .keyup();
 */
</script>

Solution

  • You could do it like this.

    $("#textinput").keyup(function() {
      var value = $(this).val();
      if (value.indexOf("24004") > -1) {
        $('#textinput2').val("My new value");
      }
      if (value.indexOf("24005") > -1) {
        $('#textinput2').val("My new value");
      }
    })
    

    You could also use value.includes('24004') instead of the indexOf

    Demo

    $("#textinput").keyup(function() {
      var value = $(this).val();
      if (value.indexOf("24004") > -1) {
        $('#textinput2').val("My new value");
      }
      if (value.indexOf("24005") > -1) {
        $('#textinput2').val("My new value");
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input list="listname" id="textinput" name="textinput" type="text" value="" required />
    <datalist id="listname">
        <option value="24004 - Name1 - Street1 - Place1">
        <option value="24005 - Name2 - Street2 - Place2">
        <option value="24006 - Name3 - Street3 - Place3">
    </datalist>
    
    <input id="textinput2" name="textinput2" type="text" value="" required />