I have a database from which I generate options for the user to select from. Based on this selection, I submit these values to the same page and get the selections using javascript.
In the same form, I have a radio buttons and a multiple selection menu.
The html is generated as such:
Radio button and multiple option selection code:
htmlstr+="<select multiple>";
for (i=0; i<g.length;i++) {
htmlstr+="<option name='ges[]' value='" + g[i] + "'>" + g[i] + "</option>";
}
htmlstr+="</select><br>";
for (i=0; i<st.length;i++) {
htmlstr+="<input type='radio' name='sts' value='" + st[i] + "'>" + st[i] + "<br>";
}
These are both placed within a form, which then has a submit button.
Upon clicking the submit button, I want to know the values of the selections. I understand the multiple selection will be an array, but how do I get the array of values, and I cannot even get the value of the selected radio button. I have already tried getting the value using the .value attribute attached to the name, however this does not work.
There is not a real simple way of doing it. You'll have to check each option.
There is a HTMLSelectElement.selectedOptions interface that is documented. But it's not used much and I'm not sure of the browser support. Plus, it only applies to the select control and not the radio controls. You can check it out here though: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
But for a more reliable method, try this...
For the select control, iterate through the selectControl.options array, and check each item for a selected attribute. If the selected attribute is true, then add that value to your own array.
Pseudocode:
for (var i in select.options) {
if (select.options[i] && select.options[i].selected) {
selectedOptions.push(select.options[i].value);
}
}
For the radio buttons, iterate through the array of objects in the dom (getElementsByName), and check the checked attribute. It it is true, add that value to your array.
Pseudocode:
for (var i in radios) {
if (radios[i] && radios[i].checked) {
selectedOptions.push(radios[i].value);
}
}
Here is a full working sample using your code:
jsFiddle: https://jsfiddle.net/mspinks/u890j86j/3/
Related
The following gif should show the problem in action.
Typeahead seems to trigger the onChange function before actually setting the value from a click, for who knows what reason.
As you can see whatever is typed into the box is grabbed correctly, but if a user selects an option from the dropdown only what had been typed in up to that point is grabbed, rather than the appropriate behavior which is the value in the text-box.
The TypeAhead JS code looks like
$('#typeahead_id').typeahead({
name: 'typeahead',
remote: 'search.php?key=%QUERY,
limit: 10
});
And the html for the input
<label>Team Name:</label>
<input type='text' id='typeahead_id' onChange='update_params("team",typeahead_id)' class='typeahead tt-query' autocomplete='on' spellcheck='false' placeholder='Select Team'><br>`;
The update Param method
function update_params(val, id) {
let temp = nodes[id]
temp.params[val] = $("#" + val + id).val()
console.log(temp)
}
The oddness of this can be explained in that each of the blue boxes is referred to as a node, and can have their own unique typeahead.
I need a way in that users can type the name of the team into the input or select one from the dropdown and my code should be able to retrieve that value and set it in the appropriate spot.
I am working on a site which connects to a MySQL database and lets you display/edit the data in it. The site uses JavaScript and PHP, with HTML and CSS parts (these are added using JS).
The site works, does everything I wanted it to do, but only from PC. When I try to use it from a smartphone, some of the hidden fields' value doesn't get submitted correctly to the PHP page responsible to working with them.
First, I have a few of this select box:
var maxLvl;
var select = document.createElement( 'select' );
var trooplist = [archerLvl, giantLvl, wizardLvl, balloonLvl, dragonLvl]; //this array contains numbers, which will be used to set the starting option in the select
select.id = "select" + k + " " + i; //k and i are both variables in their respective for loop: k goes from 0 to 2, in it there's another with i.
select.onblur = function() {
var selectid = this.id;
var last = selectid.slice(-1);
if(last==0){
document.getElementById("hiddenArcherid").value = this.value;
alert(document.getElementById("hiddenArcherid").name + " " + document.getElementById("hiddenArcherid").value);
}else if(last==1){
document.getElementById("hiddenGiant").value = this.value;
alert(document.getElementById("hiddenGiant").name + " " + document.getElementById("hiddenGiant").value);
}else if(last==2){
document.getElementById("hiddenWizard").value = this.value;
alert(document.getElementById("hiddenWizard").name + " " + document.getElementById("hiddenWizard").value);
}else if(last==3){
document.getElementById("hiddenBalloon").value = this.value;
alert(document.getElementById("hiddenBalloon").name + " " + document.getElementById("hiddenBalloon").value);
}else if(last==4){
document.getElementById("hiddenDragon").value = this.value;
alert(document.getElementById("hiddenDragon").name + " " + document.getElementById("hiddenDragon").value);
}
};
select.style.position = "absolute";
select.style.left = 250 + (i*(width + (width/10))) +"px";
select.style.top = 110 + height + (rowcounter * (height * 1.5)) + "px";
select.style.width = width;
if(i==0 || i==1 || i==2 || i==3)
maxLvl = 6;
else
maxLvl=4;
for(var l=0; l <= maxLvl; l++){
var option = document.createElement( 'option' );
option.setAttribute("value", l);
option.innerHTML = "Level " + l;
select.appendChild(option);
}
select.selectedIndex = trooplist[i];
IDarray.push(select.id);
document.body.appendChild(select);
This code runs in a for loop, and creates 5 select boxes using data passed by a function. Then, when the user selects a new option, the option's value is stored in a HTML hidden input field with. Like this one:
var hiddenArcher = document.createElement('input');
hiddenArcher.setAttribute("type","hidden");
hiddenArcher.name = "hiddenArcher";
hiddenArcher.id = "hiddenArcherid";
hiddenArcher.setAttribute("value", document.getElementById("select1 0").value);
formNew.appendChild(hiddenArcher);
These input fields have a basic value, which is the default of the select box - 0 if the user creates a new entry, or an already known value if the user wants to modify an already existing entry. All the input fields have the same structure, only the JS var, the name, the id and the default value changes.
The input fields are part of the formNew form, which has multiple submit buttons - pressing those buttons posts the fields' values to a PHP page, which executes the MySQL queries, depending on which button was pressed. For this, I use if/else if (isset). Then the PHP redirects (by using header("Location: http://my_sites_address"); exit();) to the main page - the one I where the select boxes are.
If I try it from Chrome, the site works - The right values get passed, the PHP executes the right queries correctly. I can add new entry, and both delete or modify existing ones. When I try it on Android (via emulator) or iOS (via my friend's phone), although I can select the values I want to change, and the alerts display the correct data, too, when I hit submit, nothing happens within the database, it seems like I did nothing. The browser gets redirected to the PHP, so I guess the submit does happen, but there will be no changes in the database. The PHP simply redirects to the main page, and that's all.
The only function can be used successfully on phone is deleting the entry, most likely because the hidden field responsible for storing the row's ID gets it's value the moment it's added to (a different) form, and the value never changes, only when the user switches to a different entry.
The hidden fields "physically" (based on their location in the file) are declared later than the select boxes.
Currently, the code acts this way on phone:
1) I start editing the entry. The select boxes show up.
2) I can select the desired value.
3) An alert pops up, confirming the value got passed to the hidden field.
4) I press the submit button, comes the PHP, then the redirects, and I am back where I started. There are no changes in the database.
I already tried to switch onchange to onblur at the select boxes; I made sure JS is enabled (which was totally unnecessary, because the images/texts displayed with JS). Right now I have no idea what's wrong.
Are any of you experienced something similar, or has any idea what should I do?
Some browsers fail to correctly and completely recognize the programmatic change of a hidden input's value immediately after it is changed. If you submit the form directly after changing the hidden input's value via javascript, the value sent for that input will be the pre-change value, rather than the value you set in javascript.
Unfortunately, I don't have a list of browsers that exhibit this behavior, nor do I know the exact mechanics behind it. What I do know is that I've run into the issue you're describing, and I have always been able to solve it by triggering a change event on the hidden input after changing its value via javascript.
For those using plain javascript with no external libraries, your code would look something like this (see here):
<input id="myHidden" name="myHidden" type="hidden" value="old value"/>
<script type="text/javascript">
var hiddenInput = document.getElementById('myHidden');
hiddenInput.value = 'new value';
console.log(hiddenInput.value); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Set up and trigger the change event on our input:
var changeEvent = document.createEvent("UIEvents");
changeEvent.initUIEvent("change", true, true);
hiddenInput.dispatchEvent(changeEvent);
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
For those using jQuery or a similar library, the code is a little more concise:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
var $hiddenInput = $('#myHidden');
$hiddenInput.val('new value');
console.log($hiddenInput.val()); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Trigger the change event on our input:
$hiddenInput.change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Really concise example (one-liner) using jQuery:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
$('#myHidden').val('new value').change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Here's a working example using a slightly simplified version of the code supplied in the original question.
In our case, the issue was simply that we had this check in PHP:
if (isset($POST['myvalue']) && !empty($POST['myvalue'])) {
// save
}
However, in PHP 0 is considered empty in PHP and thats exactly what the passed value was!
I am attempting to use the easyDropDown.js add on to style my drop boxes but I have encountered an issue. My drop box is not statically created. When the webpage is loaded an array is used to append the drop down list. This drop box appears on multiple pages of my website and I am attempting to set it up so that when the user makes a selection on one page, that selection carries to every page.
Here's a step by step play-through of what the code is doing:
When the page is started it appends the easyDropDown list so that all the values are there.
$('#homeSelectSite').empty();
s = "";
s = "<option value='site'>Site</option>";
for (var i = 0; i < Sites.length; i++) {
s = s + "<option value='" + Sites[i].SiteID + "'>" + Sites[i].SiteID + " " + Sites[i].SiteName + "</option>";
}
$('#homeSelectSite').append(s);
Note: Sites is the array that I am using to fill the drop box.
Now once the drop box list has been created I need to set what value is selected. This value is set in the sessionStorrage if the user has made a selection on another page.
$('#homeSelectSite').easyDropDown();
var selectedSite = sessionStorage.getItem("CurrentSiteID");
if (selectedSite != undefined && selectedSite != null) {
$('#homeSelectSite').val(selectedSite);
}
So what the code is doing is this: emptying the current drop box, appending it with new values, styling it with easyDropDown, and finally setting the selected value. For some reason this will not work. The appending and styleing are working just fine but it will not allow me to set the selected value. I have also tried using this:
$('#homeSelectSite').easyDropDown('select', selectedSite);
Is there a reason why I cannot set the selected value? This all works if I remove everything related to easyDropDown.
I had a similar issue today as I was trying to set the selected value of a dropdown using easyDropDown.
What I did to fix it was to find out the index of the to-be selected option, rather than selecting it by value.
In your case it would be something like:
var index = 0;
$('#homeSelectSite option').each(function(i, item) {
if ($(this).val() === selectedSite) {
index = i;
}
});
$('#homeSelectSite').easyDropDown('select', index);
Hope it helps.
it looks like there's a bug in easyDropDown 2.1.4
Line 326 should be changed from:
index = self.$select.find('option[value='+index+']').index() - 1;
to:
index = self.$select.find('option[value='+index+']').index();
This will only solve the fact that easyDropDown was selecting the previous item instead of the one you wanted, but I'm not sure this would solve your issue. And yes, you must use the 'select' method from the plugin instead of 'val'.
I have a textbox where the user puts in some text, and a dropdown appears. When the user selects something from the dropdown list, the text from the dropdown replaces the text that they typed.
Now, I want this textbox to clear itself if they didn't select anything from the dropdown.
So basically, the only text that can appear in the textbox is something that was ultimately selected from the dropdown. How would I achieve this?
I've tried:
jQuery("#" + field).focusout(function() {
jQuery("#" + field).val("");
});
But this still clears even if they selected from the dropdown. What logic would I implement to do this? Could I set a variable or something that is set to true when they select from a list. I would then check this on the focusout function?
Quite new to JQuery!
Use the autocomplete change event, check for the existence of ui (the item selected from the menu, if any. Otherwise the property is null), if it doesn't exist, then you know the user didn't select an autocomplete option, and you can empty the value:
change: function (ev, ui) {
if (!ui.item) {
$(this).val('');
}
}
Here's a simple demo fiddle
Possibly something like this:
jQuery("#" + field).focusout(function() {
var enteredValue = $("#" + field).val();
var listOfAvailableOptions = //put method call here
if($inArray(enteredValue, listOfAvailableOptions)) //possibly use IndexOf() here and check if = -1
{
jQuery("#" + field).val("");
}
});
The neater way would be to populate the values of a combo box from the AJAX call though
I'm a little new to javascript. I have a bunch of checkboxes for an html form. The checkboxes are dynamically generated from a python script. The last checkbox I have is entitled "N/A", I want to make it so that if any of the other checkboxes are checked, the "N/A" checkbox automatically disappears. If the N/A checkbox is checked, the others disappear. And of course, if I uncheck the boxes, the opposite should occur. I know that i need to assign the different input fields different id's so javascript can identify them, but I'm not sure how to write the javascript to make the actual disappearing action to occur.
Thank you.
edit;; Some dynamic python code:
print "<blockquote><strong>Labels:</strong><br/>"
for elem in output_list:
if elem not in non_delete_list:
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"" + elem + "\" />" + elem + "<br/>"
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"r_on\" />N/A:"
print_reason_list()
print "<font color=\"#cc0000\">Reason Required</font><hr/>"
So basically, anything with the value=elem part is dynamic, the final checkbox is N/A (value="r_on").
edit 2:
So I'm able to get the boxes to disappear thanks to #Ankit (using document....style.display= "none"). The issue I'm having is that once a box is checked, respective id becomes PERMANENTLY hidden. In order to fix this, I made a hide and unhide function and my onclick looks like:
"onclick=if(this.checked){hide("NA")}else{unhide("NA")}"
And that allows me to uncheck the boxes and cause the respective tags to reappear. I'm running into a new issue however. With the checkboxes of value elem. If I check two boxes, and then uncheck one of the boxes, the "NA" appears again. I want it to remain hidden as long as there is an "elem" box that is checked. Basically, I need to rescan all the checkboxes to see their current states (I think). How can I do this?
You can enable/disable an html element through javascript with:
document.getElementById('<the id of your checkbox here>').disabled = true;
For your case just put a div tag around the dynamic check boxes and add/remove that div based on your need.
Example:-
print "<blockquote><strong>Labels:</strong><br/>"
for elem in output_list:
if elem not in non_delete_list:
print "<div id=\"listBox\" >"
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"" + elem + "\" onclick=\"if(this.checked){myFunction("upperChkBoxes")}\" />" + elem + "<br/>"
print "</div>"
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"r_on\" onclick=\"if(this.checked){myFunction("NA")}\" />N/A:"
print_reason_list()
print "<font color=\"#cc0000\">Reason Required</font><hr/>"
function myFunction(par){
// put your logic of add/remove here based on par value as "upperChkBoxes" or "NA"
}
Hope that helps.
You could show or hide an html element using css property display none
to make it disappear
document.getElementById('<the id of your checkbox here>').style.display = "none";
or to show back
document.getElementById('<the id of your checkbox here>').style.display = "block";
If you are using jquery you could easily use to accomplish the same
$('#id of the checkbox').hide() or $('#id of the checkbox').show()