Displat form after clicking button - javascript

I have a question to you about JavaScript. I want to display form after clicking a button and then when I write something and click submit it must display the value of form on screen. And the problem is that when I click submit it display only for a second. Here is my JavaScript code:
window.onload = function () {
var dod = document.getElementById("dodaj")
dod.onclick = function () {
document.write("<form action='?' id='formualrz'><input id='f1' type='text' name='pole' value='Nazwa'><input id='f2' type='text' name='pole' value='Opis'><input type='submit' id='sub'></form>");
var f1 = document.getElementById("f1");
var f2 = document.getElementById("f2");
var submit = document.getElementById("sub");
submit.onclick = function () {
document.write(f1.value + "<br/>" + f2.value);
}
}
}

Your form is being submitted. Add the following to your form tag
<form onsubmit="return(false)" >
Or in your case on the event handler:
submit.onclick = function () {
document.write(f1.value + "<br/>" + f2.value);
return(false);
}
This topic explains what return false actually does.

Related

How stop function and display error message if one value is missing in JavaScript?

I'm designing a website and I need the below function to stop when one Input value is missing and display the error message.
My HTML code for the form:
<form action="http://localhost/qurantest/" method="get" target="_blank" id="my-form">
<input type="text" name="reference-number" id="reference-number" value="" class="6u 12u$(xsmall)" placeholder="enter chapter"/>
<input type="text" name="reference-number" id="reference-number2" value="" placeholder="enter verse"/>
<br>
<input type="submit" value="GO" class="button big special" />
</form>
The JavaScript function is;
<script type="text/javascript">
var form = document.querySelector('#my-form'),
text_field = document.querySelector('#reference-number');
text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
// build the new url and open a new window
var url = form.action + text_field.value + '/' + text_field2.value;
window.open(url);
// prevent the form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>
What I want is: To stop the function and display an error message when 1 of the two "inputs" (text_fields) is empty. Also, I want to assign maximum values for each input. (In my case I want the 1st input field to contain only numbers between 1-114 and the 2nd input field to contain only numbers from 2-286), and this specific function opens in a new window as the above code suggests, I want the function to open in the current window itself. How can I do this is JavaScript?
I'm new to JS so any help would be appreciated. Thanks in Advance!!
Check this one.
<script type="text/javascript">
var form = document.querySelector('#my-form');
var text_field = document.querySelector('#reference-number');
var text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
if(!text_field.value || !text_field2.value) {
console.log("error message here");
return;
}
var url = `${form.action}${text_field.value}/${text_field2.value}`;
window.open(url);
return;
}
form.onsubmit = submitHandler;
</script>
Try this
<script type="text/javascript">
var form = document.querySelector('#my-form'),
text_field = document.querySelector('#reference-number');
text_field2 = document.querySelector('#reference-number2');
function submitHandler(){
// checks values
if(text_field.value == "" || text_field2.value == "") {
alert("Message");
return false;
}
// build the new url and open a new window
var url = form.action + text_field.value + '/' + text_field2.value;
window.open(url);
// prevent the form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>

Cannot cancel form submission in jquery

I am trying to cancel form submission after button click.
When button is clicked i get some information from check-timetable-timing-conflict with json.
So i decide to cancel the form submission if the data coming with json is 1.
But it does not cancel form submission although i get 1.
<form role="form" method="POST" id="subform" name="subform">
...
...
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
}
});
}
</script>
In order to prevent the form from submitting you need to return false from the onclick function that is called when the button is clicked. Also to prevent ajax form submissions you can also add e.preventDefault(); like below.
Note: The same effect could be achieved if using the form's onsubmit method instead of the button's onclick method to call the function.
var select_course = function(e) {
e.preventDefault();
// your logic goes here
return false;
}
<form role="form" method="POST" id="subform" name="subform" >
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course(event);">placeholder</button>
</form>
Your issue is where the submit event listener is set up.
You need to move this block of code outside the check_conflict() function.
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
.submit(function(e){}) creates a handler for the submit event. In your code, you aren't creating the handler until after the check_conflict function makes it's asynchronous call returns. It's too late. You need the handler already in place when the user submits the form.
<script>
conflict = 0;
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
var select_course = function()
{
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
}
else {
// todo no conflict
}
});
}
</script>
The problem was because of asynchronous behaivor of ajax.
When i click the button, the form submission already starts.
So when i try to check the conflict condition in jquery the form submission has already finished. So i solved the problem by submitting the form just in the if condition in jquery where i get conflict=1 with document.subform.submit().
Before the solution, i was starting the form submission, then i was doing jquery checks.
But now i first make jquery checks, then i do or not do form submission according to jquery search results.
<form role="form" method="POST" id="subform" name="subform">
...
...
#DELETED THIS > <button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
#ADDED THIS > EKLE
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
} else {
document.subform.submit(); #ADDED THIS PART
}
});
}
</script>

Can't get my HTML form to NOT submit upon clicking Submit button

I have an HTML form. I'm asked to write JS code to validate the data in the form and display results of the validation on the same page, without submitting the form. I'm told to have my JS function (which executes when Submit is clicked) return false so that the form is not submitted. I did that but still when I run my page, the results of form validation flash on the page for half a second and disappear as the form is submitted. What am I doing wrong? Here's what I have in JS: (the first function adds an event listener to the submit button of my form)
function eventListener(){
var submitBtn = document.getElementById("sub");
submitBtn.addEventListener("click", validate, false);
}
function validate(){
var input1 = document.getElementById("book_1").value;
var input2 = document.getElementById("book_2").value;
var input3 = document.getElementById("book_3").value;
if(input1=="" || input2=="" || input3=="")
window.alert("Error: Please fill in all input fields");
else if(isNaN(input1) || isNaN(input2) || isNaN(input3))
window.alert("Error: Please enter numbers in the input fields");
else{
var total1 = input1*19.99;
var total2 = input2*86;
var total3 = input3*55;
var grandtotal = total1 + total2 + total3;
var container = document.getElementById("container");
var par = document.createElement("p");
container.appendChild(par);
par.innerHTML = "<h3>Basic XHTML (Quantity: " + input1 + "):</h3> $" + (total1)
+ "<br/> <h3>Intro to PHP (Quantity: " + input2 + "):</h3> $" + (total2)
+ "<br/> <h3>Advanced JQuery (Quantity: " + input3 + "):</h3> $" + (total3)
+ "<br/><br/> <h3>Final Total:</h3> $" + grandtotal;
}
return false;
}
window.onload = eventListener;
pass the event to the validate function and set a preventDefault, like this:
function validate(event){
event.preventDefault();
// your code here
}
submit the form after validation with .submit() if needed;
Just move the listener to the form:
function stopSubmit(){
return false;
}
window.onolad = function() {
document.getElementById('f0').addEventListener('submit', stopSubmit, false);
}
<form id="f0">
<input value="foo" name="foo">
<button>Submit</button>
</form>
The listener should be on the form anyway since it can be submitted without clicking the button.
PS.
The form seems to submit anyway in stack snippets, but put it in a page and the code works.

Displaying Counter on The Actual HTML Button

I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE

Javascript validation is not working when i use struts 2 jquery submit button onClick event

I am using struts2-jquery-plugin-3.2.1 . I am using submit button of it, i am calling javascript validation on onclick event but my form is submitting even though validation not done.Here is code:
<sj:submit
value="Add"
targets="idRightMainDiv"
button="true"
buttonIcon="ui-icon-gear"
formIds="addExerDetailsForm"
onclick="return SetsRepsFormValidate()" //calling javascript validation
tabindex="7"/>
function SetsRepsFormValidate() {
var summary = "";
summary += isSets();
summary += isReps();
if (summary != "") {
dhtmlx.alert(summary);
return false;
}
else {
return true;
}
}
I got solution in this link this:
put this code in head section-
<sj:head jqueryui="true"/>
<script type="text/javascript">
$.subscribe('before', function(event,data) {
var fData = event.originalEvent.formData;
alert('About to submit: \n\n' + fData[0].value + ' to target '+event.originalEvent.options.target+' with timeout '+event.originalEvent.options.timeout );
var form = event.originalEvent.form[0];
if (form.echo.value.length < 2) {
alert('Please enter a value with min 2 characters');
// Cancel Submit comes with 1.8.0
event.originalEvent.options.submit = false;
}
});
$.subscribe('complete', function(event,data) {
alert('status: ' + event.originalEvent.status + '\n\nresponseText: \n' + event.originalEvent.request.responseText +
'\n\nThe output div should have already been updated with the responseText.');
});
$.subscribe('errorState', function(event,data) {
alert('status: ' + event.originalEvent.status + '\n\nrequest status: ' +event.originalEvent.request.status);
});
</script>
And wrote struts 2 jquery submit button's events-
<div class="type-button">
<sj:submit targets="result"
value="AJAX Submit"
timeout="2500"
indicator="indicator"
onBeforeTopics="before"
onCompleteTopics="complete"
onErrorTopics="errorState"
effect="highlight"
effectOptions="{ color : '#222222' }"
effectDuration="3000"/>
</div>`
You should really add validation to the onsubmit event of the form as the form can also be submitted by hitting the enter key.
Your current validation will only fire if the user clicks on the button.

Categories