2015-07-01 4 views
0

Я борюсь с добавлением data- атрибутов в входы формы, нажав на ссылку. Если я нажму на другую ссылку, то предыдущие значения должны быть заменены новыми, связанными с этой ссылкой.Атрибуты данных в полях Значение

Это мой код ссылки:

<div id="links"> 
<h3>Links</h3> 
<a href="#1" data-url="http://apple.com" data-name="My url">Link 1</a> 
<a href="#2" data-url="http://bbc.co.uk" data-name="My second url">Link 2</a> 
<a href="#3" data-url="http://google.com" data-name="My third url">Link 3</a> 
</div> 

И это код моей формы:

<div id="form"> 
<h3>Form</h3> 
<input type="text" size="25" value=""> 
<input type="hidden" name="" value=""> 
</div> 

Так у меня только одна форма, чтобы обслуживать все ссылки (возможно, более чем 100 в итоге).

Пожалуйста, смотрите мой JSFIDDLE здесь: http://jsfiddle.net/jtzrjrs2/1/

Я очень ценю вашу помощь.

+0

Почему оба поля ввода нет имени? Какой атрибут 'data- *' предназначен для поля ''? – Andreas

+0

Могу ли я добавить атрибут data-url в свое скрытое поле ввода так же хорошо? – qqruza

ответ

1

Ваш текущий код, аннотированный:

$('#links a').click(function(){ // when I click an 'a' element within the element with ID 'links' 
    $(this).find('input').val(); //find any inputs contained within the clicked item, and get the value of the input 
}); 

Вы, наверное, хотите что-то больше, как это:

$('#links a').click(function(){       // when I click an 'a' element within the element with ID 'links' 
    $('#form').find('input').val($(this).data('name')); // find any inputs within the elmeent with id 'form', and set its value to be the 'data-name' attribute of the item I clicked 
}); 

JSFIDDLE

Update

Для установки отдельных значений в входы, т его решение должно работать:

$('#links a').click(function(){          // when I click an 'a' element within element with ID 'links' 
    $('#form').find('input[type="text"]').val($(this).data('name')); // for the element with id 'form', find all inputs of type 'text', and set the value to the 'data-name' attribute of the clicked element 
    $('#form').find('input[type="hidden"]').val($(this).data('url')); // for the element with id 'form', find all inputs of type 'hidden', and set the value to the 'data-url' attribute of the clicked element 
}); 

JSFIDDLE

+0

Спасибо @Dave Salomon Могу ли я добавить URL-адрес данных в скрытое поле ввода одновременно? – qqruza

+0

Это потрясающе @Dave_Salomon Большое спасибо !!! – qqruza

+0

Добро пожаловать. Надеюсь, что встроенные комментарии к кодовой подсказке :). –

Смежные вопросы