I have a <div class="foo">Foo</div> and I have two input fields:
<input type="submit" class="text_field" name="input_one" value="">
and<input type="submit" class="text_field" name="input_two" value="">
I would like to be able to click <div>Foo</div> and populate field #1 with the value Foo and field #2 with value Bar. (Extrapolate upon this idea to incorporate many different divs and thus, many different value combinations.) How best can I do this using jQuery?
So far I have no trouble doing something like:
jQuery(function () {
$('div.foo').click(function (e) {
var foo = $(this).text();
$("input.text_field").val(foo);
});
});
This works for clicking the div and populating one text field with the text value between the tags, i.e., “Foo”. This is a good start and all…but since I am new to this, I was wondering how might I best go about populating the two different text fields with two different said values “Foo” and “Bar”. Is there a way to set a name="Bar" or something to this effect on the div, and then access that name value to insert into the second text field input_two? Thoughts, comments, considerations appreciated, thank you!
it’s a weird question, can you explain what you NEED to do? I mean, you posted what you want to do, but why do you want to do that? it’s not clear what are Bar and Foo, are those predefined values for each submit? does the value depend on the div (let’s say you have more than one div and you need to populate the inputs depending on which div was clicked)
you can put any attribute to any tag that you need and access them using $([selector]).attr(‘attr_name’) to get the value, html5 defines some “data-” attributes to store thing like that http://html5doctor.com/html5-custom-data-attributes/
EDIT:
you can have something like
and the js
then the js is generic and you can add as many divs as you want whit any values