daninthemix
daninthemix

Reputation: 2570

jQuery - update one text input from another (and I don't know the ID)

In the below, when a user changes the Asset Tag, I want what they entered to be added to the end of the field to the left (hostname) if and only if the hostname currently has a value that ends in '-'.

Also, I don't know the exact ID or name or either of these two inputs as they're generated in PHP like this:

<input type="text" name="hostname-<?=$t;?>" class="form-control" id="hostname-<?=$t;?>">

<input type="text" name="asset-tag-<?=$t;?>" class="form-control" id="asset-tag-<?=$t;?>">

enter image description here

How can I achieve this?

EDIT - I ended up achieving what I wanted with this code (as asset-tag and hostname always share the last digit:

  $("[name^='asset-tag']").on("change", function () {
      var host = $(this).attr('name');
      var hostname = $('#hostname-' + host.substr(host.lastIndexOf("-") + 1));
      var host = hostname.val();
      if (host.slice(-1) == "-") {
        hostname.val(host = host + $(this).val());
     }
  });

Upvotes: 0

Views: 41

Answers (1)

apokryfos
apokryfos

Reputation: 40683

Basically you need:

$("[name^='asset-tag']").on("change", function () {
     var $host = $(this).prev("[name^='hostname']");
     if ($host.val().substr($host.val().length-1) == "-") {
        $host.val($host.val()+$(this).val());
     }
});

Where [name^= means "the name attribute starts with".

Note: This assumes that the host is the closest element which has a name which starts with hostname.

Upvotes: 2

Related Questions