I modified the simple example of jQuery.post as
$("#searchForm").submit(function(event) {
event.preventDefault();
var $form = $( this ),
term = $( "input[name^=tick]:checked" ).serialize(),
url = $form.attr( 'action' );
$.post( url, { ticks: term, id: '55' },
function( data ) {
$( "#result" ).empty().append( data );
}
);
});
This works for single checkbox with val() but not for multiple checkboxes in
<input type="checkbox" name="tick" value="'.$value.'" />
since serialize() should generateticks: termto be used astermin$.post`.
How can I make the serialize() to generate appropriate data for $.post
NOTE: I do not want to serialize the entire form but only checked values of checkbox INPUT.
Simple value collector :)
HTML
<input type="checkbox" class="selector" value="{value}"/>
JS
var checked='';
$('.selector:checked').each(function(){
checked=checked+','+$(this).val();
});
PHP
$ids=explode(',',substr($_GET['param_with_checked_values'],1));
You could use .serializeArray()
Ref: http://api.jquery.com/serializeArray/
In html code change name="tick" in name="tick[]" and you can use simply $(this).serialize(); to post all checked values.
You can still use .serializeArray and use it in .post() like this:
var postData = {};
var form = $('#formId').serializeArray();
for (var i = 0; i < form.length; i++) {
if (form[i]['name'].endsWith('[]')) {
var name = form[i]['name'];
name = name.substring(0, name.length - 2);
if (!(name in postData)) {
postData[name] = [];
}
postData[name].push(form[i]['value']);
} else {
postData[form[i]['name']] = form[i]['value'];
}
}
$.post('/endpoint', postData, function(response) {
}, 'json');
postData will contain all form elements except the disabled ones. All checkbox values will be passed as an array just like when doing a normal form submission.
let $form = $(".js-my-form");
let $disabled = $form.find(':input:disabled').removeAttr('disabled');
let formData = {};
$.each($form.serializeArray(), function (index, fieldData) {
if (fieldData.name.endsWith('[]')) {
let name = fieldData.name.substring(0, fieldData.name.length - 2);
if (!(name in formData)) {
formData[name] = [];
}
formData[name].push(fieldData.value);
} else {
formData[fieldData.name] = fieldData.value;
}
});
$disabled.attr('disabled', 'disabled');
console.log(formData);
Its a variation of Stanimir Stoyanov answer with possibility to serialize disabled fields.
term = $("#input[name^=tick]:checked").map(function () {
return this.value;
}).get();
term.join();
Related
I have the following hidden input field on my form:
<input class="dow" id="hidden_dow0" type="hidden" value="m,t,w,r,f,s,n">
Once the form has loaded I need to find this hidden control, extract the value... and then use each item in the list ('m,t,w ') to set corresponding checkboxes on
So far, I have been able to find all hidden inputs, but I don't know how to extract the value from it.
Here's what I have so far:
$('.dow ').each(function (i, row) {
var $row = $(row);
var $ext = $row.find('input[value*=""]');
console.log($ext.val); //fails.
});
EDIT 1
This is I tried:
//find all items that have class "dow" ... and
$('.dow ').each(function (i, row) {
var $row = $(row);
console.log(i);
console.log(row); //prints the <input> control
//var $ext = $row.find('input[value*=""]');
var $ext = $row.find('input[type="hidden"]');
console.log($ext); //prints an object
$ext.each(function() {
console.log( $(this).val() ); //does not work
});
});
In jQuery val() is a function.
The .dow element is the input, you don't need to find it
$('.dow ').each(function (i, row) {
console.log( $(this).val() ); //works
});
I have page Search.asp (code below). And Filtered.asp which include Search.asp.
<%
Dim CheckForCheckboxes
CheckForCheckboxes = Request.form("chkBoxes")
response.write "CheckForCheckboxes" & CheckForCheckboxes
%>
<div id="ExSearch" name="ExSearch" >
<script>
// on page load check if this page called from POST and have passed checkboxes to select
var str = '<%=CheckForCheckboxes%>'; // {"Make[]":["AIXAM","CADILLAC","JEEP"],"selCountry[]":["5","4","8"]}
if (!str || str.length === 0) {} else {
var Checked = JSON.parse(str);
// alert works here
// This one not work
$("#ExSearch").find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
// alert do not work here
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
});
};
// from here function which select checkboxes and hold them in hidden input field before submit, on submit pass this object with form
$(function() {
$('div.list input[type=checkbox], input[type=radio]').on('change',onValueChange);
$('div.selector select').on('change', onValueChange);
function onValueChange() {
var Checked = {};
var Selected = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {Checked[name] = [];}
Checked[name].push($el.val());
});
// Hold all dropdowns
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (!!$el.val()) {Selected[name] = $el.val();}
});
// Put all together to POST
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(Selected) + "&" + $.param(Checked),
dataType: 'text',
success: function (data) {
// Put response data to page and reselect checkboxes, this works good
$("#ExSearch").html(data).find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
if (Selected[name]) {$el.val(Selected[name]);}
});
// Hold converted object to string values
$("<input type='hidden' value='' />").attr("id", "chkBoxes").attr("name", "chkBoxes").attr("value", JSON.stringify(Checked)).prependTo("#ajaxform");
}
});
};
});
</script>
<form name="ajaxform" id="ajaxform" action="Filtered.asp" method="POST">
</form>
</div>
So If page Search.asp starting I check if object passed via form post method, and if passed I need to select checkboxes which is in this object.
So I create object, then I convert it to string with Json.stringify and then catch form post string and convert back to object with JSON.parse
So everything look ok but checkboxes is not selecting and no errors appears.
What now is wrong?
Note what your code loading first and then loading your all divs so $("#ExSearch").find( cant find any checkboxes.
Try to put your <script></script> code after </form>
Here's a link
<form onsubmit="return false"></form>
<label for="quantity">qantity</label>
<select name="quantity">
<script>
for (var i = 1; i < 81; i++) {
document.write("<option value='"+i+"'>"+i+"</option>");
};
</script>
</select>
<button id="next">next</button>
<form id="itemform" onsubmit="return false"></form>
<script>
$('#next').click(function(){
var quantity = ($('select[name=quantity]').val());
$('#itemform').html("");
for (var i = 0; i < quantity; i++) {
$('#itemform').append("<label for='itemname"+i+"'>itemname</label><br><input type='text' name='itemname"+i+"' id='itemname"+i+"'><br><label for='itemprice"+i+"'>itemprice</label><br><input type='text' name='itemprice"+i+"' id='itemprice"+i+"'><br><br>");
};
$('#itemform').append("<button id='submit'>submit</button>");
});
$('#submit').click(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
It creates text inputs as many as selected.
And then, it makes object like {itemname1 : "an awesome thing", ...}.
Creating input works very well but it doesn't make object.
It makes object input that doesn't created dynamically.
<form onsubmit="return false">
<input type="text" name="first">
<input type="text" name="second">
<input type="submit" id="submit">
</form>
<p id="res"></p>
<script>
$('#submit').click(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
</script>
Why doesn't it work as I expected?
$('#submit') doesn't exist in your example. I replaced it with $('#itemform').submit() instead, and it seems to be logging a giant object. See the updated jfiddle here.
$('#itemform').submit(function(e){
e.preventDefault();
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
Also, if you're looking at improving how items are stored, I updated the jsfiddle again here to show you how you can group items:
$(document).ready(function() {
$('#next').click(function(){
var quantity = ($('select[name=quantity]').val());
$('#itemform').html("");
for (var i = 0; i < quantity; i++) {
$('#itemform').append("<div class='item' data-item='" + i + "'><label for='itemname"+i+"'>itemname</label><br><input type='text' name='name' id='itemname"+i+"'><br><label for='itemprice"+i+"'>itemprice</label><br><input type='text' name='price' id='itemprice"+i+"'><br><br></div>");
};
$('#itemform').append("<button id='submit'>submit</button>");
});
$('#itemform').submit(function(e){
e.preventDefault();
var items = {};
$('#itemform div.item').each(function(){
var item = {};
$(this).find('input[type=text]').each(function() {
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
items[$(this).data('item')] = item;
});
console.log(items)
});
});
This yields a much better object you can work with:
{
"0": {
"name": "item1name",
"price": "item1price"
},
"1": {
"name": "item2name",
"price": "item2price"
},
"2": {
"name": "item3 here",
"price": "item3 has a big price"
}
}
Don't attach your processing function to your form's submit button's click event. Instead, use the form's submit event.
Also, even though it doesn't make a difference syntax wise, for readability's sake, you might want to add a ";" after "console.log(item)".
$('#itemform').submit(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item);
return false;
});
Also, no need for a onSubmit property on your form in your case, just return "false" with the processing function attached to your form's submit event.
<form id="itemform"></form>
See the updated fiddle here.
I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.
I'm working on editable table using FLASK, JSON and Jquery
I have serialised form and sent via $.getJSON you can see in the bottom of my JS code:
Here is the JS code:
$(function(){
$('tbody').on('click', 'td', function() {
displayForm( $(this) );
});
function displayForm (cell) {
var column = cell.attr('name'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width')
prevContent = cell.text(),
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" size= "4" value="'+prevContent+'"/><input type="hidden" name="id" value= "'+id+'" />'+'<input type="hidden" name="column" value="'+column+'"/></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width', cellWidth);
cell.on('click', function() {return false;});
cell.on('keydown', function(e) {
if (e.keyCode == 13) {
changeField(cell, prevContent);
} else if (e.keyCode == 27) {
cell.text(prevContent);
cell.off('click');
}
});
}
function changeField(cell, prevContent) {
cell.off('keydown');
var url = '/jsonurl?',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data){
if (data.success)
cell.html(data.value);
else {
alert('There was a problem updating the data.');
cell.html(prevContent);
}
});
cell.off('click');
}
});
and in the Processing side I use Flask to handle this data but when I edit the form and press enter to submit form it says: File "/Users/Team/Desktop/Flask/routes.py", line 72, in
jsonurl column = request.args.GET('column')
AttributeError: 'ImmutableMultiDict' object has no attribute 'GET'
What does this mean? It seems like I handle the JSON in the wrong way. Can anyone tell me what is the right way to handle this data?
Here are the codes in Processing side (which I think it is wrong and need your suggestion):
#app.route('/jsonurl')
def jsonurl():
column = request.args.GET('column')
id = request.args.GET('id')
newValue = request.args.GET('newValue')
g.db = connect_db()
cur = g.db.execute('UPDATE customer SET column = newValue WHERE rowid=id')
g.db.commit()
g.db.close()
return jsonify(success=True, value=newValue)
Use lowercase 'get' instead of 'GET' with request.args below:
request.args.get('column')
.args contain GET parameters.