Reputation: 33
I'm trying to manipulate the values of a hidden field, without submitting the form. The closest I found is Add and Remove values in a hidden field array
Problem I have with this is that it submits the form. In my project I'm not ready to submit the form yet. There are more questions to be asked. Here's a JSFiddle of my problem.
I feel like I'm missing something like a 'return false'.
Thanks for the help.
jQuery.fn.extend({
addToArray: function(value) {
return this.filter(":input").val(function(i, v) {
var arr = v.split(',');
arr.push(value);
return arr.join(',');
}).end();
},
removeFromArray: function(value) {
return this.filter(":input").val(function(i, v) {
return $.grep(v.split(','), function(val) {
return val != value;
}).join(',');
}).end();
}
});
Upvotes: 0
Views: 230
Reputation: 3130
You can add return false;
in the onClick code:
<button onclick='$("#myField").addToArray("21"); return false;'>
To prevent submission.
I think you should ask a separate question, but I'm diving into this anyway. I modified the HTML in the jFiddle. Since you're using jQuery I took advantage of the click event handler. Initially I created a single handler to see what code was required. It looked like this initially:
$( "#strength" ).click(function() {
event.preventDefault();
if ($( '#goals' ).val().indexOf(',strength') >= 0) {
$( '#goals' ).val($( '#goals' ).val().replace(',strength', ''));
$( this ).removeClass('button');
$( this ).addClass('buttonSelected');
} else {
$( '#goals' ).val($( '#goals' ).val() + ',strength');
$( this ).removeClass('buttonSelected');
$( this ).addClass('button');
}
});
That was an okay starting point to figure out the required code. However I didn't want to repeat that code for each of the buttons. So I factored out the code that I knew could be reused for the other buttons. So it looked like this:
$( "#strength" ).click(function() {
event.preventDefault();
toggle(',strength', this);
});
function toggle(str, thisObj) {
if ($( '#goals' ).val().indexOf(str) >= 0) {
console.log(str + ' is already selected');
$( '#goals' ).val($( '#goals' ).val().replace(str, ''));
$( thisObj ).removeClass('buttonSelected');
$( thisObj ).addClass('button');
} else {
console.log(str + ' is about to be selected');
$( '#goals' ).val($( '#goals' ).val() + str);
$( thisObj ).removeClass('button');
$( thisObj ).addClass('buttonSelected');
}
}
Then it is pretty straightforward to handle the additional buttons with some repetitive code:
$( "#weight" ).click(function() {
event.preventDefault();
toggle(',weight', this);
});
$( "#tone" ).click(function() {
event.preventDefault();
toggle(',tone', this);
});
You may be able to decrease the repetition, but I'm tired and hungry. Hope this helps you out!
Upvotes: 0
Reputation: 5473
Solution is to preventdefault event.
Here's the solution:
event.preventDefault();
Upvotes: 0