IZenteno09
IZenteno09

Reputation: 13

Modify multiple a href targets with input values

1) I want to add multiple input values, each with an "OK" button and its a tag.

2) When the "OK" button is pressed, it changes the href value of its a tag to the input tag value whose "OK" button was pressed.

Like this: https://jsfiddle.net/tzLac9zt/8/

(Code in fiddle)

1) Is done, problem is 2)

Tried this but did not work:

var number_button = $('button[name=boton1]');
var number_link = $('input[name=linknum1]');

document.querySelector('number_button').addEventListener("click", function() {

  // Store value
  var valor = $('number_link').text(value);

  // change href value
  $('a[name=descarga1]').attr('href', value);

});

Tried to do it first for a single case, then for everyone.

Calling them through their names so I can catch the specific value that I want to change, dont know if this is the proper way to do it though.

Upvotes: 0

Views: 199

Answers (1)

Rafik Tighilt
Rafik Tighilt

Reputation: 2101

Well, here, I simplified a bit you "cloning" code, using the clone method. I also added a class to the buttons so I can select all of them and bind a click listener to execute what you want to achieve.

The trick is simple here, clone the first controls, then empty the textfield and the href attribute of the cloned element children, then show them to the screen. Given the class of the button and the listener on that class, you will automatically have the behavior you want without writing a lot of code and this is due to the usage of siblings which returns the specified siblings of an element.

Here is a fiddle for demo :

$(document).ready(function(){
	$("#addrow").on('click', function() {
  	var clone = $('.controls').first().clone(true);
        clone.find('a').attr('href', '');
        clone.find('input[type=text]').val('');
        clone.appendTo('.ytlink').hide().slideDown();
  })
  
  $('.goBtn').on('click', function() {
	var link = $(this).siblings('a');
        var input = $(this).siblings('input[type=text]');
  	link.attr('href', input.val());
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ytlink">
  <div class="controls controls-row">
    <input class="span3" placeholder="Insert Link" type="text" name="linknum1">
    <button type="button" class = "goBtn" name="boton1">Ok</button>
    <a href="" name="descarga1"> go to this inputs href </a>
   </div>
 </div>
 <a href="#" id="addrow"><i class="icon-plus-sign icon-white"></i> Add </a>

Upvotes: 1

Related Questions