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

<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.

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 do my JavaScript calls not work in a form after switching the doctype to HTML5

I have a form that uses JavaScript to reveal additional fields depending on user selections. The code worked fine using the XHTML 1.1 doctype (not my choice... lame school project guidelines), but after switching to the HTML5 doctype nothing works. The only way I can get any JavaScript to work inside the form is to put it directly in the onchange="" setting; just adding the function call there will not work. I've tried event listeners also, and that doesn't work either.
For simplicity's sake I'm only showing code for one of the dynamic fields:
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
document.getElementById("visitor").addEventListener("change", function(ev) {
Visitor();
});
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
document.getElementById("vother").innerHTML=(othertext);
}
}
</script>
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor" onchange="Visitor();">
<option value="" disabled selected style="display:none;">select...</option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
</body></html>
I'm aware that other people have asked similar questions, but none of the answers I've found work for me.
I verified some issues in your code:
this line is not valid (syntax error):
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
You should escape the double quotes, or replace them with single quotes.
This will work:
var othertext = "<label>What would you consider yourself?</label><br/><input type=text name='other_visitor' id='other_visitor' />";
Get rid of the inline onchange="Visitor(); binder or the document.getElementById("visitor").addEventListener. You should choose one of the approachs.
move your <script> tag to the bottom of your body (just before </body>). Or wrap your code into DOMContentLoaded event (IE9+).
(optional). You don't need parenthesis around (othertext) here:
document.getElementById("vother").innerHTML = (othertext);
Working code: https://jsfiddle.net/mrlew/txk11m6c/
You should put your script at bottom like given below or use window.onload.
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor" onchange="Visitor();">
<option value="" disabled selected style="display:none;">select...</option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
<script type="text/javascript">
document.getElementById("visitor").addEventListener("change", function(ev) {
Visitor();
});
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
document.getElementById("vother").innerHTML=(othertext);
}
}
</script>
</body></html>
Here's my two cents:
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() { // ~ F I X ~ Run code when the rest of page is done loading instead of immediately when browser reads it. This is a very common problem I've noticed newbies have with JS
document.removeEventListener("DOMContentLoaded",this); // Remove event after it's served purpose
document.getElementById("visitor").addEventListener("change", Visitor); // Also removed redundant function, Visitor can already be called by itself
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type=\"text\" name=\"other_visitor\" id=\"other_visitor\"/>"; // Backslashed quotations that were clearly meant to be included part of string
document.getElementById("vother").innerHTML=(othertext);
}
}
});
</script>
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor">
<option value="" disabled selected style="display:none;">select... </option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
</body></html>

Displaying text with JavaScript from multiple conditions in form

In this question I would like to display some HTML text depending on a which combination of options is selected in a form. In this example for instance, I want to display some text if spelling is selected as a subcategory and 'greater-depth' (equivalent to an 'A' grade) is selected as the performance grade. I've developed this in Rails form_for but have shown the form as rendered in the browser.
<form class="new_english_grade" id="new_english_grade" action="/english_grades" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="VTtOS/86shuyQPW6/HfaduffmQiVXLiJb06IQp7+56LM8cD8KRnD3qLGbQBit4OuAIc92MYbFpPObR6ePYmY1g==" />
<div class="field">
<label for="english_grade_subcategory">Subcategory</label>
<select name="english_grade[subcategory]" id="english_grade_subcategory"><option value="Spelling">Spelling</option>
<option value="Reading">Reading</option>
<option value="Writing">Writing</option></select>
</div>
<div class="field">
<label for="english_grade_performance_grade">Performance grade</label>
<select name="english_grade[performance_grade]" id="english_grade_performance_grade"><option value="Not-started">Not-started</option>
<option value="Working-towards">Working-towards</option>
<option value="Working-at">Working-at</option>
<option value="Greater-depth">Greater-depth</option></select>
</div>
</form>
The text I'd like to display for instance is like:
<div id = "spelling_greater_depth">
This text is displayed only if 'spelling' and 'greater-depth' are selected in options
</div>
I have initially set my CSS to be:
#spelling_greater_depth
{
display: none;
}
My JavaScript is not really working yet so I have not included it but I was trying to implement it using this:
I think this might be enough to get you started https://jsfiddle.net/sxh0n7d1/37/
However it is very difficult to answer the question, can you clarify your question or give feedback to this answer if it is close?
$('select[name="english_grade"]').change(function () {
$('#spelling_working_at').css("display","none");
console.log($(this).val());
var fieldToShow = $(this).val();
$("#" + fieldToShow).css("display","block");
});

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.

Changing SELECT OPTION dropdown data with button click

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>

Categories

Resources