Reputation: 21
I'm redesigning a signup form for my company. Unfortunately, I feel like I'm in over my head on this one. lol.
What I need to do is create a web form for a mobile themed site. I've got the site more or less functioning using JQuery Mobile at the moment, but I'm struggling with the form input aspect of it all. One of the things this form needs to do is be able to populate 3 fields when the user taps a button.
So for example, if I have a button that says "Turkey, Mashed Potato & Wine"... when the user taps that button, the 3 fields below it would populate with the values "Turkey", "Mashed Potato" and "Wine".
Is there any way this is possible?
Upvotes: 1
Views: 1098
Reputation: 1157
Yes, this is possible. One way to do it is place the values in an data attribute and append them.
Working example: http://jsfiddle.net/vj3Zg/
Upvotes: 1
Reputation: 13630
Try this:
$(function(){
$('#my_button').on('click', function(e){
$('#field_one').val('Turkey');
$('#field_two').val('Mashed Potato');
$('#field_three').val('Wine');
});
});
I'm assuming, however, that you would need this to work dynamically based on the text of the button. If so, you'd have to work out some string manipulation to get the values:
$(function(){
$('#my_button').on('click', function(e){
var parts = $(this).attr('value').split(',');
// do some more work here to clean up the values,
// you'd need the values separated with commas all
// the way through (ie: Turkey, Mashed Potato, Wine)
$('#field_one').val(parts[0]);
$('#field_two').val(parts[1]);
$('#field_three').val(parts[2]);
});
});
Upvotes: 1
Reputation: 145408
I would do it as follows, if only I got you right.
HTML:
<form>
<input type="text">
<input type="text">
<input type="text">
</form>
<button data-val="Turkey|Mashed Potato|Wine">Turkey, Mashed Potato & Wine</button>
JavaScript:
$("button").on("click", function() {
var val = $(this).data("val").split("|");
$("form input").val(function(i) {
return val[i] || "";
});
});
DEMO: http://jsfiddle.net/8aHtP/
Upvotes: 2
Reputation: 31131
You can use jQuery's .val()
to set the value of a textbox.
<div id="pop">Turkey, Mashed Potato & Wine</div>
<input type="text" id="f1" />
<input type="text" id="f2" />
<input type="text" id="f3" />
$("#pop").click(function() {
$("#f1").val("Turkey");
$("#f2").val("Mashed Potato");
$("#f3").val("Wine");
});
Upvotes: 1