How do I make this Jquery dry?
// Adding data to input depending on what div is clicked
$('#navninfoDiv').click(function() {
$('input#webhost_navninfo').data('myData', null);
});
$('#navninfoDivP').click(function() {
$('input#webhost_navninfo').data('myData', 'p');
});
$('navninfoDivV').click(function() {
$('#inputwebhost_navninfo').data('myData', 'V');
});
// Adding data to input depending on what div is clicked
$('#prisinfoDiv').click(function() {
$('#inputwebhost_prisinfo').data('myData2', null);
});
$('#prisinfoDivP').click(function() {
$('#inputwebhost_prisinfo').data('myData2', 'p');
});
$('#prisinfoDivV').click(function() {
$('#inputwebhost_prisinfo').data('myData2', 'V');
});
// Adding data to input depending on what div is clicked
$('#cableinfoDiv').click(function() {
$('#inputwebhost_cableinfo').data('myData3', null);
});
$('#cableinfoDivP').click(function() {
$('#inputwebhost_cableinfo').data('myData3', 'p');
});
$('#prisinfoDivV').click(function() {
$('#inputwebhost_cableinfo').data('myData3', 'V');
});
// Adding data to input on submit
$('#smt').click(function() {
// for input#webhost_navninfo
var myData = $('#webhost_navninfo').data('myData'),
val = $('#webhost_navninfo').val();
if (myData) {
$('#webhost_navninfo').val(myData + val);
}
// for input#webhost_prisinfo
var myData2 = $('#webhost_prisinfo').data('myData2'),
val2 = $('#webhost_prisinfo').val();
if (myData2) {
$('#webhost_prisinfo').val(myData2 + val2);
}
// for input#webhost_cableinfo
var myData3 = $('#webhost_cableinfo').data('myData3'),
val3 = $('#webhost_cableinfo').val();
if (myData3) {
$('#webhost_navninfo').val(myData3 + val3);
}
});
How do I dry all this code up? I have many more input fields about 50.
Here is my HTML and jQuery without the data functions: http://jsfiddle.net/z5qeX/2/
The code example I gave in this example is just to illustrate the functionality I want. It does not match the HTML in the jsfiddle, but it is the code I want to add it to later.
Here is my simple solution with very less script provided you add couple of data attributes into all 3 types of div's as mentioned below. Also instead of using
mydata
,mydata2
andmydata3
we can just usemydata
as data attribute name for all types of input.Here is the working demo
Markup
Js
I hope this helps you.