onsubmit doesn't display text [duplicate] - javascript

I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
How do I make it so that the insertion of HEADING remains permanent?

Move the listener to the form's submit handler. Have the function return false to stop submission:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
<input type="submit">
Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
There is an error in your code, it's missing a closing double qoute:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.

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.

hello message function in js [duplicate]

I am new to javascript and on every simple thing i get some kind of problem but this seems un-solve-able to me. I googled and nothing simillar.
After i input data into textbox and store it into variable, i print out variable in paragraph.
Problem is that output i printed out disappears within less than second. Code seems to be normal, what might it be? It looks like c when you dont put getch();
Thanks in advance.
<form>Unesite broj koji ce se ispisat kasnije.<br>
<input type="text" id="userInput">
<input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()"><br><br>
</form>
<br><br>
<p>Unjeli ste <b id="ispis"></b></p>
<script>
function unesi(){
var userInput = document.getElementById('userInput').value;
document.getElementById('ispis').innerHTML = userInput;
}
</script>
The <form> tag doesn't specify an action attribute, so when you click the submit button, the browser will submit the form to the current URL - which will look a lot like the page is refreshing.
If you want to run the unesi function when the user clicks submit and prevent the HTML form from submitting, you need to change it slightly:
<input type="submit" name="unos" value="Unesi i ispisi"
onclick="unesi(); return false;">
The return false prevents the form from submitting itself.
Because the form submits and refreshes the page. Cancel the form request.
<input type="submit" name="unos" value="Unesi i ispisi" onclick="return unesi()">
and the function
function unesi(){
var userInput = document.getElementById('userInput').value;
document.getElementById('ispis').innerHTML = userInput;
return false;
}
better option is to do it on the form level
<form action="#" method="get" onsubmit="return unesi()">
Instead of cancelling the form submitting, another option is to change
<input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()">
to
<input type="button" name="unos" value="Unesi i ispisi" onclick="unesi()">
This will make it so the form does not try to submit at all when the button is pressed.

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()">

Two forms on the same page needs the value of the same element

I have two forms on a php page. They post to different pages when they are submitted. Both forms need the value of a dropbox that is inside form A. How do I get this value posted when form B is submitted?
Create a hidden input in form B and put a change event on the dropdown in form A which copies it's value to that.
Example (using jQuery - if you want to do it with another library or plain javascript you'll need to adapt it).
<script type="text/javascript">
$(function(){
$('#copy-src').change(function(){
$('#copy-target').val( $(this).val() );
}).change();
});
</script>
<form id="a" action="/a">
<input type="text" name="a_only" />
<select id="copy-src" name="also_b">
<option value=""></option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
<button type="submit">Submit</button>
</form>
<form id="b" action="/b">
<input type="text" name="b_only" />
<input type="hidden" name="also_a" id="copy-target" />
<button type="submit">Submit</button>
</form>
The .change(function(){}) creates a change event to copy the value while the final .change() triggers that event (on page load) to ensure the value is right initially.
You can copy dropbox value to Form B while submitting;
On formB;
<form onsubmit="getDropdownValue()">
.....
</form>
And in function;
function getDropdownValue() {
var formB = document.getElementById("formB");
// Get selected value from FormA
var e = document.getElementById("formADropdown");
var value = e.options[e.selectedIndex].value;
// Append it to formB
var input = document.createElement("input");
input.type = "hidden";
input.name = "dropdownValue";
formB.appendChild(input);
}
You can see demo: Demo . I demo when you click submit, you will see dropdownvalue from form A will be copied to formB before submit

Validate a form without submitting

I have the following code that checks to see that two select fields are identical. The code works alright when called with onsubmit. However after doing this validation the form is still submitted. How can i prevent the script or my form from submitting the incorrect data.
Please see code below:
var fieldalias="Email address field"
function verify(element1, element2) {
var passed=false
if (element1.value=='') {
alert("Please fill out the "+fieldalias+"!")
element1.focus()
}
else if (element2.value=='') {
alert("Please verify the "+fieldalias+"!")
element2.focus()
}
else if (element1.value!=element2.value) {
alert("The two "+fieldalias+"s do not match")
element1.select()
}
else
passed=true
return passed
}
You didn't include your HTML, so I'm going to assume you've added onsubmit() to your form element.
If so, make sure your call looks like this:
onsubmit="return verify(element1, element2)"
(replace element1 and element2 accordingly)
If this assumption is not correct, please include some additional detail so we can better assist.
Try calling stopImmediatePropagation() on the event to prevent any further processing of the submit event by any other handlers in the form element or higher level elements.
Call that code with different event, like i.e: onchange, or onfocusout. This way the validation will be performed every time user enter some values to your fields, certainly before submitting.
EDIT:
I'm not sure if I understand you correctly but I would have attached your JS code this way:
First assign your select box to the variable:
var object_input = document.getElementById("selectId");
And then:
if(object_input.addEventListener)
{
object_input.addEventListener('blur', focus_lost);
object_input.addEventListener('keypress', checkForEnter);
}
else
{
object_input.attachEvent('onblur', focus_lost);
object_input.attachEvent('onkeypress', checkForEnter);
}
and then perform your validation ith focus_lost or checkForEnter.
Assuming that in the html code you have something like this:
<form action="test2.html" method="post" onsubmit="return verify(e1, e2);">
<input type="text" name="e1" /><br/>
<input type="text" name="e2" /><br/>
<input type="submit" value="Validate" />
</form>
You have to put in onsubmit event:
return verify(e1, e2);
so you will not go to the submiting page if the data is not valida
EDIT:
I think the problem is the
element1.select()
in the 3rd if, that this select method does not exist for a select object.
You can use a
element1.focus()
The code that will work is:
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false;
if (element1.value==''){
alert("Please fill out the "+fieldalias+"!");
element1.focus();
}
else if (element2.value==''){
alert("Please verify the "+fieldalias+"!");
element2.focus();
}
else if (element1.value!=element2.value){
alert("The two "+fieldalias+"s do not match");
element1.focus();
}
else
passed=true;
return passed;
}
And
<form action="test2.html" method="post" onsubmit="return verify(document.getElementById('e1'), document.getElementById('e2'));">
<select id="e1">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<select id="e2">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<input type="submit" value="Validate" />
</form>

Categories

Resources