I have a form with a bunch of checkboxes and input fields. I'm using jquery(1.10.1) to manipulate a number of things about the form based on user input from another form on the page. This was all working a few weeks ago but suddenly I've found that none of the checkboxes are submitting after they are changed by jquery.
The checkboxes are of the form:
<input type="checkbox" id="prod_70" name="prod[70]" class="product style_1 color_1 lens_3 status_1 " value="1" checked />
My Jquery code looks the other form to decide which boxes the user is interested in and then creates a selector based on that and the classes assigned to the checkboxes checking the boxes requested by the user:
$(curSel).prop('checked',true);
I was using:
$(curSel).attr('checked','checked').prop('checked',true);
But simplified since that shouldn't be necessary. I also tried adding a .change() for good measure but that didn't solve the problem so I took it back out.
When I submit the form none of the checked checkboxes show up and $_POST['prod'] (PHP on the backend) isn't there. $_REQUEST['prod'] is also not there. The other fields on the form are submitting. And if I submit the form without letting jquery update anything then the checkboxes do submit and $_POST['prod'] is as expected.
I've used the console in chrome and firebug in firefox to inspect the checkboxes while interacting with the page and 'checked' is being added and removed and the checkboxes are displaying correctly even when they're not submitting.
I've checked the HTML on the page to make sure everything is valid and there aren't any missing close tags or nested tags and the only other JS on the page are for FB's like button and twitters follow button.
I'm at a loss as to what could be causing this and my searches aren't turning up anything similar anymore.
EDITING TO ADD MORE:
After more debugging it appears that the problem isn't with changing the checkboxes. It's happening when the <li> that the checkboxes are in is hidden with .hide() and then reshown with .show(). After doing that the checkboxes in the <li> are never submitting even though other form elements inside the <li> are. Here's a full <li>:
<li class="prod style_1 color_1 lens_7 status_1 bulk-list-item" id="prod_55">
<div class="bulk-prod-name">
<input type="checkbox" id="prod_55" name="prod[55]" class="product style_1 color_1 lens_7 status_1 " value="1" />
<label for="prod_55">
<span class="style-name">Player</span>
<span class="color-name">Matte Black</span> |
<span class="lens-name">Rose Hi-Def LTD 17/35</span>
<span class="part-number">PLMBHD03</span>
<div style="margin-top:10px;">
<span class="bulk-prod-status">Status: <b>In Stock</b></span>
</div>
</label>
</div>
<div class="bulk-prod-image">
<div style="position:absolute; top:0;"><img style="width:100%;" src="/art/products/11/1/frame/thumb/1.png"></div>
<div style="position:absolute; top:0;"><img style="width:100%;" src="/art/products/11/1/lens/thumb/7.png"></div>
<div style="clear:both;"></div>
</div>
<div class="bulk-prod-price">
MSRP: $ <input type="text" id="prod_msrp_55" name="prod_msrp[55]" class="msrp inputbox" value="179.00" prod_id="55">
<input type="hidden" id="prod_msrp_orig_55" class="orig_price" value="179.00" orig_id="prod_msrp_55">
Dealer Price: $ <input type="text" id="prod_dprice_55" name="prod_dprice[55]" class="dprice inputbox" value="90.00" prod_id="55">
<input type="hidden" id="prod_dprice_orig_55" class="orig_price" value="90.00" orig_id="prod_dprice_55">
</div>
<div class="bulk-prod-edit">
Edit this product.
<div style="display:none" id="files_55">
<table width=100%>
<tr>
<td width=50% valign=top><small>Fullsize:<br>
<span style="color:#009900"> /art/products/11/1/frame/full/1.png</span><br>
<span style="color:#009900"> /art/products/11/1/lens/full/7.png</span><br>
</small>
</td>
<td width=50% valign=top><small>Thumbnais:<br>
<span style="color:#009900"> /art/products/11/1/frame/thumb/1.png</span><br>
<span style="color:#009900"> /art/products/11/1/lens/thumb/7.png</span><br>
</small>
</td>
</tr>
</table>
</div>
</div>
</li>
And here's the full jQuery that's hiding/showing/checking/unchecking things:
$(document).on('change', '.prod_selector', function(e) {
// console.log('Selection changed:');
e.preventDefault();
$('.prod').hide();
$('.product').prop('checked', false);
var lens = $('#lens_selector').val();
var color = $('#color_selector').val();
var style = $('#style_selector').val();
var pstatus = $('#status_selector').val();
var curSel = '';
if (lens>0) {
curSel += '.lens_' + lens;
}
if (color>0) {
curSel += '.color_' + color;
}
if (style>0) {
curSel += '.style_' + style;
}
if (pstatus>0) {
curSel += '.status_' + pstatus;
}
if ((lens==0) && (color==0) && (style==0) && (pstatus==0)) {
curSel = '.prod';
$('.product').prop('checked',true);
}
// console.log('curSel: ' + curSel);
$(curSel).show()
$(curSel).prop('checked',true);
$('#prod_count').text($('.prod:visible').length);
});
After messing with things I've determined that if I don't .hide() anything then it all work as expected (other than not hiding things that need to be hidden) but if any <li>'s are hidden then even once their shown again checkboxes inside of them don't get included in the form submission even though other input fields do.
I see a semi-colon missing:
$(curSel).show()
$(curSel).prop('checked',true);
The missing semicolon can stop the second statement from setting any checkbox as checked.
Problem solved. Turns out I was asking the wrong question. After more testing I finally determined that it wasn't jquery causing the problem after all.
The problem was more items were added to the database that this page manages which added more fields to the form and we were hitting the max_input_vars limit in the php config. Which I realized could be causing the issue after finding this: Limit of POST arguments in html or php
I raised the max_input_vars for this site and now the form is working again.
Related
I'm trying to wrap my head around this and trying to improve my Javascript ability. I am using ASP.NET Core MVC to create a basic web form and I've got Javascript that will run when a radio button is selected.
Razor
<div class="form-row">
<div class="form-group col-sm-4">
<label class="bold" asp-for="PhoneSetup"></label>
<br />
<input type="radio" asp-for="PhoneSetup" name="PhoneSetup" value="true" onclick="phoneSetupSelect()" /><label>Yes</label>
<input type="radio" asp-for="PhoneSetup" name="PhoneSetup" value="false" onclick="phoneSetupSelect()" /><label>No</label>
</div>
</div>
Javascript
<script>
function phoneSetupSelect() {
var formInput = document.getElementById("myForm");
var phoneSetupValue = formInput.PhoneSetup.value;
//alert(phoneSetupValue);
console.log('phoneSetupValue = ' + phoneSetupValue);
if (phoneSetupValue == 'true') {
document.getElementById('hiddenDiv').classList.remove("hidden");
}
else {
document.getElementById('hiddenDiv').classList.add("hidden");
}
}
</script>
Aside from the if condition shown in the script, I tried the following
if(phoneSetupValue == true) and if(phoneSetupValue)
with mixed results. The former does not work, despite the model property being of type bool and the latter DOES work, which I understand why. In that case, since the same script is attached to both radio buttons, the value being present on either will trigger the true condition.
I got it to work but I'm just confused as to why and if there are ways I can make this better and less "hacky" feeling.
I am just starting out with JQuery for asp.net core mvc.
I have a section of a page comprising a list of items linked to the main subject. When an 'edit' button is clicked against one of the list items, a hidden section (fieldset) is displayed and populated with the values of that list item. Other inputs on the page are disabled and the user can edit the item. All works fine.
However, when finished editing, the user clicks a 'submit' button (within the previously hidden fieldset) and the idea is to submit the edited data via ajax and, if accepted, to update the list. Ajax, etc. is not (yet) the problem.
When the user clicks the 'submit' button (coded as type="button"), the values in the edited section appear to have been cleared and are returned as spaces or nulls. It only seems to apply to this fieldset, as (disabled) values from the remainder of the document can be retrieved (just for testing purposes).
Can anyone tell me what is going on here and how to preserve these edited values, please?
#**** Drop-down section for editing Admissions ****#
<fieldset id="AdmissionsEditFieldset" class="app-edit-main-fieldset" hidden>
<legend id="AdmissionsEditLegend" class="app-edit-fieldset-legend">Editing Admission</legend>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
<div class="form-group">
<strong><label>Institution:</label></strong>
<span class="app-label-to-input-sep">
<input id="admId" name="aId" type="text" class="form-input app-can-disable" asp-for="Admission.Id" hidden />
<select id="admPlace" name="aPlace" type="text" class="app-can-disable" asp-items="Model.PlaceOfDetentionDd" asp-for="Admission.PlaceId"></select>
</span>
<strong><label class="app-input-fld-sep">Date Admitted:</label></strong>
<span class="app-label-to-input-sep">
<input id="admDate" name="aDate" type="text" class="form-input app-can-disable" asp-for="Admission.DateAdmitted" style="width: 5%" />
</span>
<strong><label class="app-input-fld-sep">Sequence:</label></strong>
<span class="app-label-to-input-sep app-can-disable">
<input id="admSeq" name="aSeq" type="text" class="form-input" asp-for="Admission.Seq" style="width: 5%" />
</span>
<span>
<button id="admSubmitBtn" class="btn btn-sm btn-primary app-adm-edit-btn" type="button">Submit</button>
<button id="admCancelBtn" type="button" class="btn btn-sm btn-danger app-button-to-button-sep">Cancel</button>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
</div>
</div>
And this is the JavaScript/JQuery
$(document).ready(function () {
$('.app-adm-edit-btn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// btn has format 'editN[N...]'
var btn = event.target.id;
var sid = btn.substring(4);
//*** Un-hide the editing drop-down
$('#AdmissionsEditFieldset').removeAttr('hidden');
//*** Copy values from the relevent line in the table to the editing drop-down
$('#admId').val($('#ident' + sid).text());
$('#admPlace').val($('#placeN' + sid).text());
$('#admDate').val($('#dateAdm' + sid).text());
$('#admSeq').val($('#seq' + sid).text());
//*** Set the section legend
$('#AdmissionsEditLegend').text('Editing an Admission');
//*** Disable other sections
DisableFieldsets(); // Works OK - makes no difference if commented out
//*** Focus the first input box
$('#admPlace').focus();
}); // $('.app-adm-edit-btn').click
/*----------------------------------------------------------------------------------
Admissions Submit button click handler
----------------------------------------------------------------------------------*/
$('#admSubmitBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// Just to verify nothing wrong with JSON.stringify
var id = $('#admId').val();
var placeId = $('#admPlace').val();
var seq = $('#admSeq').val();
var dateAdmitted = $('#admDate').val();
var court = $('#Court').val();
// Not integrated, so that I can display the values
var jsn = JSON.stringify({
Id: $('#admId').val(),
PlaceId: $('#admPlace').val(),
Seq: $('#admSeq').val(),
DateAdmitted: $('#admDate').val()
});
$.ajax({
url: "api/EditAdmissionApi",
method: "POST",
contentType: "application/json",
data: jsn,
success: function (data) {
alert("Ajax Success"); //TODO
}
});
alert(jsn);
//TODO
});
/*------------------------------------------------------------------------
Admissions Cancel button click handler
--------------------------------------------------------------------------*/
$('#admCancelBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
});
}); // $(document).ready
/*===========================================================================
Helper Functions
===========================================================================*/
/*---------------------------------------------------------------------------
DisableFieldsets Helper function to disable fieldsets while input of linked
items takes place
---------------------------------------------------------------------------*/
function DisableFieldsets() {
DoDisableFieldsets('#MainFieldset');
DoDisableFieldsets('#AdmissionsFieldset');
DoDisableFieldsets('#ChildrenFieldset');
DoDisableFieldsets('#SubmitButtonsNonFieldset');
}
function DoDisableFieldsets(id) {
var xId = $(id);
$('.app-can-disable', xId).attr('disabled', 'disabled');
$(xId).addClass('app-disabled-background');
}
Yes it does and many thanks for the suggestion, mj.
Trying to see why and testing alternatives brought me to the real issue, however. I have to confess that it was one of those stupidities that you can stare at for hours without seeing. Still I will confess, in case it helps anyone else.
I had given the Edit buttons in the list a 'dummy' class name to make selection easier. Then I had inadvertently copied and adapted the button html to be the Submit button following edit, without deleting the class. So both the Edit and Submit button handlers seemed to be called, which was causing havoc (I have not yet worked out why this was not just producing the unedited text in the second handler - but life's too short). So a dumb question on my part - sorry for wasting everyone's time.
The construct $('#admId').val($('#ident' + sid).text()); works fine now.
I am programming a web application which accepts barcodes from a barcode reader in an input field. The user can enter as many barcodes that s/he wants to (i.e. there is no reason for a predefined limit). I have come up with a brute force method which creates a predefined number of hidden input fields and then reveals the next one in sequence as each barcode is entered. Here is the code to do this:
<form id="barcode1" name="barcode" method="Post" action="#">
<div class="container">
<label for="S1">Barcode 1   </label>
<input id="S1" class="bcode" type="text" name="S1" onchange="packFunction()" autofocus/>
<label for="S2" hidden = "hidden">Barcode 2   </label>
<input id="S2" class="bcode" type="text" hidden = "hidden" name="S2" onchange="packFunction()" />
<label for="S3" hidden = "hidden">Barcode 3   </label>
<input id="S3" class="bcode" type="text" hidden = "hidden" name="S3" onchange="packFunction()" />
<label for="S4" hidden = "hidden">Barcode 4   </label>
<input id="S4" class="bcode" type="text" hidden = "hidden" name="S4" onchange="packFunction()" />
<label for="S5" hidden = "hidden">Barcode 5   </label>
<input id="S5" class="bcode" type="text" hidden = "hidden" name="S5" onchange="packFunction()" />
</div>
<div class="submit">
<p><input type="submit" name="Submit" value="Submit"></p>
</div>
</form>
<script>
$(function() {
$('#barcode1').find('.bcode').keypress(function(e){
// to prevent 'enter' from submitting the form
if ( e.which == 13 )
{
$(this).next('label').removeAttr('hidden')
$(this).next('label').next('.bcode').removeAttr('hidden').focus();
return false;
}
});
});
</script>
This seems to be an inelegant solution. It would seem to be better to create a new input field after each barcode has been entered. I have tried creating new input elements in the DOM using jQuery, and I can get the new input element to show. But it uses the onchange event, which detects changes in the original input field. How do I transfer focus and detect onchange in the newly created input field? Here is the code that I have played with to test out the idea:
<div>
<input type="text" id="barcode" class="original"/>
</div>
<div id="display">
<div>Placeholder text</div>
</div>
<script src="./Scripts/jquery-2.2.0.min.js"></script>
$(function () {
$('#barcode').on('change', function () {
$('#display').append('<input id='bcode' class='bcode' type='text' name='S1' autofocus/>')
});
});
</script>
Once I have these barcodes, I pack them into array which I then post them to a server-side script to run a mySQL query to retrieve data based on the barcodes, and then post that back to the client. So part of what I have to achieve is that each barcode that is entered into the different input fields need to be pushed into an array.
Is there an elegant way to accomplish the creation of input fields dynamically and then detecting changes in those to create yet more input fields?
The dynamic update you have tried out is all right. If you must push it into an array on submit you have to prevent default of form submit, serialize the form and then make an ajax request.
Heres an example:
$('form').on('submit',function(e){
e.preventDefault();
var formData = $(this).serializeArray();//check documentation https://api.jquery.com/serializeArray/ for more details
$.ajax({
type:'post',
url:<your url>//or you could do $('form').attr('action')
data:formData,
success:function(){}//etc
})
});
If you do not display the barcodes in the html you can skip the input fields and store the read barcodes in an array[]. Not everything that happens in javascript has to be displayed in the website (View) . i do not know what code you use to scan the barcode but you do not need the input-elements at all.
See the example on this site https://coderwall.com/p/s0i_xg/using-barcode-scanner-with-jquery
instead of console.log() the data from the barcode scanner can simply be saved in an array[] and be send from there.
If you want to create elements dynamcially see this thread: dynamically create element using jquery
The following code adds the p-element with the label "Hej" to the div "#contentl1"
`$("<p />", { text: "Hej" }).appendTo("#contentl1");`
UPDATE: I added some simple CSS to make each input field display on its own line.
Here's one strategy:
Listen for the enter/return key on the input box.
When the enter/return key is pressed (presumably after entering a barcode), create a new input box.
Stop listening for the enter key on the original input and start listening for it on the new input.
When a "submit all" button is pressed (or when tab is used to shift the focus from the most recent input to the "submit all" button and enter is pressed), then collect all the input values in an array.
$(function() {
var finishBarcode = function(evt) {
if (evt.which === 13) {
$(evt.target).off("keyup");
$("<input class='barcode' type='text'/>")
.appendTo("#barcodes")
.focus()
.on("keyup", finishBarcode);
}
};
var submitBarcodes = function(evt) {
var barcodesArr = $(".barcode").map(function() {
return $(this).val();
}).get();
$("#display").text("Entered Barcodes: " + barcodesArr);
};
var $focusedInput = $('.barcode').on("keyup", finishBarcode).focus();
var $button = $('#submitAll').on("click", submitBarcodes);
});
input.barcode {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Type barcode into input box</li>
<li>To enter barcode and allow new entry, press Return</li>
<li>To submit all barcodes, either press tab and then return or click Submit button</li>
</ul>
<div id="barcodes"><input type="text" class="barcode" /></div>
<div><button id="submitAll">Submit all barcodes</button></div>
<div id="display">Placeholder text</div>
I need to grab the code from another part of my page without putting it in the form… is there a way to do it with JavaScript/jQuery?
Essentially, I’d like to take the value from here:
<div class='span5' style='margin-left:0px !important;'>
<label for='area0'>
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;'>
West Palm Beach
</label>
</div>
And put it into the form that exists elsewhere on the same page.
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
MORE INPUTS
</form>
Is there a simple JavaScript way to do this? I just want to take the value if the checkbox is checked and assign it as a value within the form so that it gets passed on to send_mail.php.
You can add a hidden field inside the form, like:
<input type="hidden" id="area_is_checked" name="area_is_checked" />
Then use JQuery to get the checkbox value before submitting the form:
$("#final_form").submit(function () {
$("#area_is_checked").val($("#area").is(':checked'));
return true;
});
Sure!
$('form#new-location').append($("div#move-me-please"));
Here's a jsFiddle: http://jsfiddle.net/zwxPt/
Edit: since the answer was edited after I wrote this:
If you really can't add a hidden field to the form, you can still add extra data to your form when the user submits it by submitting it via ajax. See this stackoverflow question for more info.
You can use the form attribute (works in at least Opera 9.5+, Safari 5.1+, Firefox 4+, Chrome 10+):
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;' form="final_form">
There is a Modernizr test for it. You can however still use the form attribute, and then search for those instead of hard-coding the external inputs like the following:
$('#final_form').on('submit', function() {
$('input[form=' + this.id + ']').each(function() {
var externalInput = $(this);
// then same as below.
});
});
Or using jQuery instead of the form attribute:
$('#final_form').on('submit', function() {
var externalInput = $('#area');
var name = externalInput.attr('name');
/* use existing */
var hidden = $(this).find('input[name=' + name + ']');
/* create a new hidden field */
if ( ! hidden.length ) {
hidden = $('<input>', {
name: name
}).appendTo(this);
}
hidden.val(externalInput.is('[type=checkbox]') ? externalInput.prop('checked') : externalInput.val())
});
This will create a hidden field or, if you're doing validation on it and it might not actually submit, use one that was already added. This requires not update to the HTML.
Yes, there is..
<div id="inputsBlock" class='span5' style='margin-left:0px !important;'>
<label for='area0' style="display: none;">
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;'>
West Palm Beach
</label>
</div>
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
MORE INPUTS
</form>
<script>
$('#inputsBlock').children().clone().css({display: 'none'}).appendTo($('#final_form'));
</script>
I have an INPUT text field, a DIV and an IMG.
The IMG has an onClick event:
reads the INPUT field's current value,
increase it with 1,
does a calculation with the increased value,
writes the result into the DIV.
The value of the INPUT is always increased the right way and the DIV's innerHTML always gets the right result but nothing changes in display. The displayed numbers always stay the same even if everything is done correctly in the "background".
The funny thing in it that I used the same operation at another place on the same site and there everything works and displays perfectly.
Here is the function:
function priceCalculator(max_amound,price,id)
{
var amound = parseInt(document.getElementById('sell_amound_' + id).value);
max_amound = parseInt(max_amound);
if (amound < max_amound)
{
amound = amound + 1;
document.getElementById('sell_amound_' + id).value = amound;
var item_value = amound * price;
document.getElementById('price_' + id).innerHTML = item_value;
alert(document.getElementById('sell_amound_' + id).value + ',' + document.getElementById('price_' + id).innerHTML);
}
}
And here are the elements within a PHP code:
<img src="images/plus.png" onclick="priceCalculator(\''.$bag_items[$i]['amound'].'\',\''.$bag_items[$i]['infos']['price'].'\',\''.$i.'\')" />
<form>
<input id="sell_amound_'.$i.'" type="text" readonly value="1" />
</form>
<div id="price_'.$i.'">'.$bag_items[$i]['infos']['price'].'</div>
The alert at the end of the function shows the right values but the displayed values stay the same.
It's a really simple action... What could be the problem?
EDIT:
After loading the source code of an "item" looks like this (these parts are created with loops from database, and, of course, I removed the irrelevant styling from the code and those many divs are there because of them):
<td>
<img id="item_pic_3" src="images/potions/3.png" onClick="shopSellInfo('3')" />
<div>26</div>
<form>
<input type="hidden" id="selected_item" value="" />
</form>
<div id="item_3" style="display: none;">
<span>blah...</span><br />
<span>
<br />blah...<br /><br />
<div>
<div>
<img src="images/increase.png" onclick="priceCalculator('26','10','3')" /><br />
</div>
<div>
<form>
<input id="sell_amound_3" type="text" readonly value="1" />
</form>
/26
</div>
</div>
<br />
<div id="price_3">10</div>
</span>
</div>
</td>
shopSellInfo('3') is the function that makes item_3 displayed at the right place.
Can you please view source and show what is output by:
<div id="price_'.$i.'">'.$bag_items[$i]['infos']['price'].'</div>
Check that the div id is corresponding to the JavaScript's.
EDIT: item_3 has CSS style display: none, that is why changes are not showing up.
I solved the problem!
The problem was that the IDs appeared at another place, too, so the function didn't know where to change the values because of the duplicated IDs.
Anyway, thanks your answers and will for help!