ClubCola
ClubCola

Reputation: 69

Change link HREF attribute when input value changes

I want to manipulate the HTML code (a link target), depending on the value of a form input. As soon as the value of the input is changed by the user, I want the value of the link target to be updated.

<a href="/#SINGULAR/.htm">foo</a>
<input type="text" name="singular" id="singular">
<script>
$('#singular').on('input', function() {
  //Change the link HREF.
});
</script>

Upvotes: 1

Views: 2010

Answers (2)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12872

You should use keyup event if you want to do some actions when something is typed in the textbox. To get the value of this textbox, you can use val() method of this reference (which will point to needed textbox).

$('#singular').on('keyup', function() {
    console.log($(this).val());
});

Or:

$('#singular').keyup(function() {
    console.log($(this).val());
});

Upvotes: 1

Taplar
Taplar

Reputation: 24965

So you have the binding, so now you just need to target the link and change it. I suggest putting a class or id on it.

$(selector).prop('href', newValue);

if you want to just take whatever they type in the input as the new value it would just be

$(selector).prop('href', this.value);

$('#singular').on('input', function() {
  $('#myLink').prop('href', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/#SINGULAR/.htm" id="myLink">foo</a>
<input type="text" name="singular" id="singular">

Upvotes: 5

Related Questions