This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I cannot figure out why my script is not triggering. I am trying to create form validation for this select element, requiring that is the Other option is chosen, then the following input field be set as required. As it is, the other_lab input field is not becoming required when Other is chosen in the select element. Here is the code:
<form id="form_1" method="post">
<label for="lab">Lab</label>
<select id="lab" required name="lab">
<option disabled selected value="">Choose lab</option>
<option value="Lab_1">ABC</option>
<option value="Lab_2">DEF</option>
<option value="Other">Other</option>
</select>
<label for="other_lab">If other, please specify: </label>
<input name="other_lab" id="other_lab" size="15">
</form>
<script type="text/javascript">
var form = document.getElementById('form_1');
form.onsubmit = function (e){
if(document.getElementById('lab').value == "Other") {
document.getElementById('other_lab').setAttribute("required","");
}else{
document.getElementById('other_lab').removeAttribute("required","");
}
}
</script>
I don't think it has any effect if onsubmit you add a required-attribute on any of the input elements. That is only going to affect the next submit.
Instead, if you want to make sure the form submit doesn't go through, use
e.preventDefault();
inside the condition that you need to prevent it on. This will cancel the submit, and the added required attributes can take effect on the next submit.
You can solve this by binding that same function on selectbox's change event.
Use document.getElementById instead with the form id as a parameter, you used it with your other elements, why don't you use it with the form as well?
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
var form = document.getElementById('form_1');
form.onsubmit = function(e) {
alert('submit');
}
<form id="form_1" method="post">
<label>Lab</label>
<select id="lab" required name="lab">
<option disabled selected value="">Choose lab</option>
<option value="Lab_1">ABC</option>
<option value="Lab_2">DEF</option>
<option value="Other">Other</option>
</select>
<label for="other_lab">If other, please specify: </label>
<input name="other_lab" id="other_lab" size="15">
<input type="submit" value="submit" />
</form>
document.getElementsByTagName returns a NodeList, not a single DOM node.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
notice the s in Elements which signals that it returns some form of collection.
I suggest you have a look at this page to learn about HTML forms:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
Related
So I have a form that submits device,color and the problem(with the device) and it displays the correct price underneath nicely using jQuery but I can't figure out how to insert the jQuery result into the hidden input value so that it also sends the price to next page(checkout page) Thanks :)
<form method="POST" action="../action.php">
<select class="custom-select mr-sm-2" name="device" id="inlineFormCustomSelect">
<option value="Motorola Edge">Moto Edge</option>
<option value="Motorola Edge Plus">Moto Edge Plus</option>
</select>
<select class="custom-select mr-sm-2" name="color" id="inlineFormCustomSelect">
<option selected>Select Color..</option>
<option value="Solar Black">Solar Black</option>
<option value="Midnight Magneta">Midnight Magneta</option>
</select>
<select class="custom-select mr-sm-2" name="issue" id="inlineFormCustomSelect3">
<option data-price="£0.00" data-total="" selected>Select Problem..</option>
<option data-price="£40.00" data-total="£42.00" value="Screen Repair">Damaged Screen</option>
<option data-price="£15.00" data-total="£15.75" value="Battery Replacement">Battery Replacement</option>
<option data-price="£35.00" data-total="£36.75" value="Audio Repair">Faulty Audio</option>
<option data-price="£35.00" data-total="£36.75" value="Mic Repair">Faulty Microphone</option>
<option data-price="£35.00" data-total="£36.75" value="Cam Repair">Faulty Camera</option>
</select>
<p><i id="price"></i>+Additional Fees</p>
<p>Total:<span id="total"></span></p>
<script type="text/javascript" language="javascript">
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
$('#price').html(selected.data('price'));
$('#total').html(selected.data('total'));
}).change();
});
*//This is some code I tried below//*
$(document).ready(function(){
$('input[id="price"];').val(price);
});
</script>
<input type="hidden" id="price" name="price" value=''>
<button type="submit" name="submit">
In the case that you are trying to use the same values in an entirely different page. You should know that JS variables do not automatically save, you will lose them after refreshing the page or loading another page.
In order to save variables in the browser, you can use localStorage or localSession. In this particular case, I suggest localSession. localSession will delete the data when the browser is close or the cache is cleared.
Also, you could remove the semicolon ';' from $('input[id="price"];').val(price)
I do not suggest using localStorage or localSession for important forms, this requires back-end. You could use PHP, Node, Django, or any back-end for managing forms. But what you tried was ultimatly right, it's just that there was no variable set to retrive the data from. Hence, why the input could be left empty.
One way you can do this is to update the hidden field when you update the text field.
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
$('#price').html(selected.data('price'));
$('#total').html(selected.data('total'));
$('#hiddenPrice').val(selected.data('price'));
}).change();
});
HTML:
<input type="hidden" id="hiddenPrice" name="hiddenPrice" value="">
Notes:
In your question, the hidden input has the same Id as the text field. That's not valid HTML. So give your hidden input a different Id (such as id='hiddenPrice'). Also, be aware that hidden fields can still be modified by a user. You should validate the posted price in your server side code to verify it is the correct price.
Try these
$('select[name="issue"]').on('change', function() {
var issue = parseFloat($(this).children("option:selected").data('price'));
$('input[name="price"]').val(issue);
// or this one below
$('input[name="price"]').val(issue).trigger('change');
});
Also, try changing the id of your hidden input field and remove or extract this '£' from the data-price.
I'm getting the following error:
Uncaught TypeError: Cannot set property 'sort' of undefined
I am getting the same error when trying to set other variables, target and search.
I can't see what I'm doing wrong. I'm intending setting variables which I can pass to a backend php script which will then submit a request in order to sort search results. This should be simple but I'm not sure what the problem is.
How do I set these variables so that I can submit the form?
HTML:
<div class="sort">
<form name="loop54" action="cart.php" target="_self" method="get">
<select id="sortBy">
<option value="Rel" selected="selected">Relevance</option>
<option value="PriceLoHi">Low to High</option>
<option value="PriceHiLo">High to Low</option>
<option value="A-Z">A-Z</option>
<option value="Z-A">Z-A</option>
</select>
</form>
</div>
JavaScript:
var selectmenu = document.getElementById("sortBy");
selectmenu.onchange=function() {
var selectedOption = this.options[this.selectedIndex];
document.loop54.target="_self";
document.loop54.sort = selectedOption;
// the line below refers to another form and works
document.loop54.search = document.ds_search.search.value;
document.loop54.submit();
}
I created a jsfiddle and it works there. Must be a problem elsewhere.
You have to set the name attribute for the <select id="sortBy"> element:
<select id="sortBy" name="sort">
If you want to send data to your PHP script using an HTML form, you should not manipulate the JavaScript object representing your HTML form.
The behaviour of your HTML form is this : if it contains fields with a name parameter (input tags with values, select tag with options selected), they will be sent in the HTTP Request, in an array where :
the name of the field is the entry
the value of the field is the value
So instead of doing what you do, you should :
add a input text field named "search" where your user will type his search query
add a name parameter to your select
Here's what it would look like :
var selectmenu = document.getElementById("sortBy");
selectmenu.onchange= function() {
// you can keep using JavaScript to submit your form, but select your form with its id :
document.getElementById("loop54").submit();
}
<div class="sort">
<form id="loop54" pname="loop54" action="cart.php" target="_self" method="get">
<select id="sortBy" name="sortBy">
<option value="Rel" selected="selected">Relevance</option>
<option value="PriceLoHi">Low to High</option>
<option value="PriceHiLo">High to Low</option>
<option value="A-Z">A-Z</option>
<option value="Z-A">Z-A</option>
</select>
<input type="text" name="search_ds"></input>
</form>
</div>
That way, you should end-up, server-side, with a $_GET variable containing an key/value for each of your fields : sortBy and search.
If you have a form consisting of a multi-select of say 50 options followed by a text-box, holding the ctrl key is the way we normal select multiples, but sometimes your 32 clicks in and well things happen... Now you've selected one or none. So, what I want to know is if it is possible to create a checkbox that when checked all clicks within a specific select field are treated as if ctrl is being held down when left click occurs.
<form action="" method="post">
<input type="checkbox" name="marker" value="1"> Click here to select multiple<br>
<select multiple style="width:50%" name="employees[]">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
|
|
|
v
50 more here
</select> <br>
Your message here:<br>
<textarea name="msg" style="width:50%"></textarea><br>
<input name="submit" type="submit" value="submit" />
</form>
With JQuery you can easily manipulate <select>, see .val() function. With it you can know what are selected and you can add what you want to the selection.
This is a possible script solution.
Based on this solution
$('option').mousedown(function(e) {
if ($('#marker').is(":checked")) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
}
});
i am trying to submit values of form.
but all values other than a <select> field is not submitted because i think its inside div element as shown in code below
<form action="next.php" method="post">
<input>....
<input>....
<input>....
<select name="asdf"> <!--This field submitted successfully -->
<option value="wtevr"> </option>
<option value="wtevr2"> </option>..........
</select>
<div>
<select name="asdf2"> <!--problem is here submitting this field -->
<option value="wtevr11"> </option>
<option value="wtevr22"> </option>..........
</select>
</div>
</form>
I used div because this is part of my ajax code through which i update the values in select field.
Is there any alternative solution to submit this select field form?
MY approach:
I think that there is a solution if i use a hidden input field in this form whose value get equal to value of select field before submitted the form.
<input type="hidden" value="<!--comes from JavaScript code -->">
I am new to JavaScript so any help is appreciated..
You could use:
<select name="asdf2" id="asdf2" onchange="setField();">
<option value="this">this</option>
<option value="that">that</option>
</select>
<input type="hidden" id="hiddenField" value="nothingYet">
<script type="text/JavaScript" language="JavaScript">
function setField() {
toWhat = document.getElementById("asdf2").value
document.getElementById("hiddenField").value = toWhat;
}
</script>
In any case. If all you're doing is submitting the form, there really is no reason for that value to be ignored. How are you retrieving the values?
Use a 'name' tag in your inputs, then they'll be submitted.
like this:
<form action="next.php" method="post">
<input name="foo" value="var"/>
</form>
The <select> tag has a property called [form=""].
With that you can assign it to a form element.
As the form gets submitted, the select element is included.
<form name="myform">
<input type="text" name =...>
<select name="selectelement" form="myform">
<input type="submit">
</form>
I have a form containing only select fields, a submit button and a reset button.
<form id="search_form">
<select id="country">
<option value="-1">Select Country</option>
<option value="22">USA</option>
<option value="23">Germany</option>
...
</select>
<select id="regions">
<option value="-1">Select Region</option>
...
</select>
<input type="reset" value="Reset />
</form>
Each of the select fields has a default option with a value of "-1".
When a user clicks on the reset button, I want all the selects to show the option with this "-1" value as being selected.
What is the best way to do this using JQuery?
You can just make a single .val() call, like this:
$("#search_form select").val("-1");
Or the entire handler:
$("#search_form input:reset").click(function(e) {
$(this).closest("form").find("select").val("-1");
e.preventDefault();
});
You can give it a try here, though if you're just using this to default the values instead of resetting them, I'd use a button instead of a type="reset".