Changing SELECT OPTION dropdown data with button click - javascript

I'm trying to manipulate dropdown lists through javascript, but I seem to get this code every time I click a button:
TypeError: objDropDownMenu.options is undefined
objDropDownMenu.options[1].selected = true;
Here is my code:
<FORM NAME="myform" ACTION="" METHOD="GET">
<SELECT class="select diff_data" style="WIDTH: 165px" name=CarPick>
<OPTION value=1>Audi</OPTION>
<OPTION value=2>BMW</OPTION>
<OPTION value=3>Mercedes</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button2" Value="Write" onClick="writeText(this.form)">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
var objDropDownMenu = document.getElementsByName("CarPick");
function writeText (form) {
objDropDownMenu.options[30].selected = true;
}
</SCRIPT>
Anyu idea why? Thanks!

getElementsByName always returns an array of objects.
So you have to use:
objDropDownMenu[0].options[30].selected = true
A better way to approach this is to set an ID for your select and then use document.getElementById('yourid') which will always return just one object (since the ID should always be unique in a HTML document).

I'm not sure, if your code is just an example, but if not, there many unmatching names. Lets fix that:
<FORM NAME="myform" ACTION="" METHOD="GET">
<SELECT class="select diff_data" style="WIDTH: 165px" name="CarPick">
<OPTION value="1">Audi</OPTION>
<OPTION value=2>BMW</OPTION>
<OPTION value=3>Mercedes</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button2" Value="Write" onClick="writeText(this.form)">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
var objDropDownMenu = document.getElementsByName("CarPick")[0]; //It is get elementS - all alements with that name are returned
function writeText (form) {
objDropDownMenu.options[2].selected = true; //Here I wonder if 30th entry exists, 2 surelly does
}
</SCRIPT>

Related

Submit a form via this object

I have a form that I want to submit, and I don't know the best way to call the form.
This is my HTML
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" /><input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil()" />
</form>
Now the Javascript, I included jQuery.
function submitFormInfoEtatCivil() {
var update = "index.php/rh/updateinfo";
var dataString = $( this ).serialize();
// dataString return <empty string>
jQuery.ajax({
});
}
I have many forms with ids : form1, form2, form3 ...
My problem is how to specify the fonction submitFormInfoEtatCivil() to get the form where button is submitted. I used $( this ).serialize() but I am wrong because the output is empty.
You can pass this inside function and then use .closest("form") to get input datas from form where button has been clicked.
Demo Code :
function submitFormInfoEtatCivil(el) {
var update = "index.php/rh/updateinfo";
//use closest to get form where button is clicked
var dataString = $(el).closest("form").serialize();
console.log(dataString)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>
<form id="form" name="form">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>
$(this) that you use refers to button and you are getting empty string when you are serialize() a button.
I strongly recommend an another solution for this problem; you can catch the form when it is submitted with the on() function;
$('form').on('submit',function(){
var thiz = $(this);
var update = thiz.attr("form-url"); //get update url from the form as an attiribute or define it staticly.
var dataString = thiz.serialize();
return false; //to prevent original form action.
});
When you use above code snippet you can remove onclick="submitFormInfoEtatCivil(this)" from your code and also if you want to deep dive with on() function, you can find here an documentation.

Why The Validation is not working for the provided html/ js code

I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required

Javascript onchange function not working on select tag

I made 2 input fields and 1 select field and I applied onchange() function to select tag which calls javascript and that script make calculation and show it in other two fields
but it is not working for some syntax or logic reasons. please take a look at my code ,any help would be appreciated.
<html>
<head>
<script type="text/javascript">
function update() {
var x = document.getElementsByName("n_person").value;
document.getElementsByName("m_income").value= x*5;
document.getElementsByName("y_income").value= x*4;
}
</script>
</head>
<body>
<div class="elist"> <span class="b_text"><span>*</span>Level 1:</span>
// here is select tag where I put onchage function <select class="ifield" name="n_person" onChange="update()">
<option value="" selected="selected">Choose no. of person referred</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// These are teh input where resultant value will appear <input type="text" value="" placeholder="Your weekly Income..." name="m_income" id="weekly_income" class="field" readonly required />
<input type="text" value="" placeholder="Your day Income..." name="y_income" id="day_income" class="field" readonly required/>
</div>
<!--elist-->
</body>
</html>
See this fiddle
Updated JS
function update() {
var x = document.getElementsByName("n_person")[0].value;
document.getElementsByName("m_income")[0].value = x * 5;
document.getElementsByName("y_income")[0].value = x * 4;
}
The problem with your JS was you was not targetting the correct HTML elements using getElementsByName.
Please read more about it here
The method getElementsByName returns, as its name indicates, a list of elements with the specified name and not just one. In your case, the names are unique to the document and the method will return a list with just one value, but you'll still need to index this list. Therefore, you must change this:
var x = document.getElementsByName("n_person").value;
to
var x = document.getElementsByName("n_person")[0].value;
Do this also for the other uses of getElementsByName and your code will work.

How to make the chosen value of select list visible

How I can make the selected choice still visible until I re-choose another one?The list may contain more than 10 options
=====
<form method="get" action="Chairman.php" >
<select name="courses" id="courses" class="styled-select" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<input type="submit" value="Search Instructor"
onClick="checkDropdown()"></input>
<div id="error" style="color:red"></div>
=====
Also when I am trying to validate the select list,The error is displayed and then quickly it disappears
<script>
function checkDropdown () {
var courses = document.getElementById('courses');
if(courses.value==="courses") {
document.getElementById('error').innerHTML="PLEASE selecttt";
return false;
}
}
</script>
The select is reset and the error disappears because the form is still posted. The value that you return from the function doesn't stop the submission.
You should use the onsubmit event on the form instead of onclick on the button. Use return in the event code to convey the value from the function back to the event:
<form method="get" action="Chairman.php" onsubmit="return checkDropdown()">

How to replace the hidden value dynmaicaly using java script in html

<form method="post" name="test" id="test">
<input type="hidden" name="listname" value="qpaustin" />
<select name="customCity" id="customCity" onchange="javascript:onChangeHiddenValue(this.value);">
<option value="qpneworleans" >qpneworleans</option>
<option selected="selected" id="listSelectionActiveOption" value="qpnewyork" >qpnewyork</option>
<option value="qporangecounty">qporangecounty</option>
<option value="qporlando">qporlando</option>
</select>
</form>
<script type="text/javascript">
function onChangeHiddenValue(cityName)
{
alert(document.getElementById('customCity').value);
}
</script>
I need to change the hidden value "listname" dynamically using javascript.
For example, currently the value of listname is qpaustin. But when i change the value to qpneworleans the "listname" value should be replaced to qpneworleans .
How to do this.
Kindly advice. Thanks in advance
A few comments:
The onchange event should be bound to the select element, no to the options.
Give your form a name, that will make the programmatic access easier, e.g. document.forms['formName']
For example:
<form method="post" name="form1">
<input type="hidden" name="listname" value="qpaustin" />
<select name="customCity" onchange="onChangeHiddenValue(this.value);">
<option value="qpneworleans">qpneworleans</option>
<option selected="selected" value="qpnewyork">qpnewyork</option>
<option value="qporangecounty">qporangecounty</option>
<option value="qporlando" >qporlando</option>
</select>
</form>
<script type="text/javascript">
function onChangeHiddenValue(cityName) {
// DOM2 standard way to access forms and elements
document.forms['form1'].elements['listname'].value = cityName;
}
</script>
Check the above example here.
Its better if you can give an id to the hidden element. Something like
<input type="hidden" id="listname" name="listname" value="qpaustin" />
and your javascript to assign value to that element will be
document.getElementById("listname").value = cityName;
Apart from the solution that Rahul has provided you can also try out the following.
document.test.listname.value = cityName;
In Javascript you can refer to form elements by their names.

Categories

Resources