Javascript onsubmit triggers parent onclick - javascript

I have a html page with a table and a form in each row. When i klick on the row it should open a detailpage, but when I click in the form this should not be triggered.
My row looks like this:
<tr onclick="window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onsubmit="return confirm('Are you sure?');">
</form>
</td></tr>
So it should work like this: if I klick in the size-field, or on the submit-button, the detail-page should not be called.
I found out that one can use event.stopPropagation() for this, but I cannot find out how to do it with plain javascript although it seems that there should be an easy solution

Try
<tr onclick="window.parent.location.href='details.php?id=123';">
<td><img /></td>
<td>text</td>
<td>price<br>
<form method="post" onsubmit="return confirm('Are you sure?');">
<input type="number" name="size" value="1" onclick="event.stopPropagation()">
<input type="submit" onclick="event.stopPropagation()">
</form>
</td>
</tr>
Note: Remove the onsubmit from input element and add it to form element. Thank you #epascarello for the correction.

Here is the solution
<tr onclick="var x = event.clientX;var y = event.clientY;if(document.elementFromPoint(x, y).tagName.toLowerCase()!='input'){window.parent.location.href='details.php?id=123'; }"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="return confirm('Are you sure?');">
</form>
</td>
</tr>

I just ran into this issue myself and this post helped me: How to stop propagating event from parent div to child div
So you'll want to set something up like this:
var parent = document.getElementsByClassName("parent")[0];
var child = document.getElementsByClassName("child")[0];
parent.addEventListener("click", function(e) {
alert("you clicked parent");
if (e.target !== this) {
return;
}
e.stopPropagation();
// parent.style.color = "green";
});
child.addEventListener("click", function(e) {
alert("you clicked child");
if (e.target !== this) {
return;
}
e.stopPropagation();
});
.parent {
width: 500px;
height: 500px;
background-color: red;
}
.child {
width: 200px;
height: 200px;
background-color: blue;
}
<div class="parent">
<div class="child">
</div>
</div>
In your case, maybe try including a script with functions to call for the onclick element properties for better readability:
<tr onclick="changeLocation(e, 'details.php?id=123')"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="return confirm('Are you sure?');">
</form>
</td></tr>
<script>
function changeLocation(e, reference) {
if (e.target !== this) {
return;
}
e.stopPropagation();
window.parent.location.href=reference;
}
</script>
Or even better a propagation event function:
<tr onclick="stopProp(this); window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="stopProp(this); return confirm('Are you sure?');">
</form>
</td></tr>
<script>
function stopProp(e) {
if (e.target !== this) {
return;
}
e.stopPropagation();
}
</script>

Thank you all - I used the solution of sanketd617 and it worked fine - sorry for the error with the onsubmit - in my file it is in the -tag - I typed it and did not copy/paste the code, since my code is a bit more complicated.
I also tried the code of Aricha but it did not work for me - it still did execute the detail-page, but maybe I made a mistake there too. I tried similar solutions before, but it never worked for me.
But I did not find the really simple solution with onclick="event.stopPropagation()" in the onclick of the input-elements. So thank you very much

Related

Enable submit button when select checkbox

I have try a few examples of enable the submit button when checkbox is selected but i'm getting nowhere. Below is one of my attempts, where the submit button is disabled until the checkbox is selected. Please let me know what am i missing.
function checked(sub1) {
var myLayer = document.getElementById(sub1);
var input = myLayer.childNodes[0];
if (input.checked == true) {
myLayer.disabled = "";
} else {
myLayer.disabled = "disabled";
}
}
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx " onchange="checked('sub1')" />
</p>
<p>
<input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled" />
</p>
Nobody has explained why your code isn't working.
For one, you aren't selecting the input checkbox element properly. It is not a child node of the button element. You could either get a reference to the checkbox by passing this in the onchange event, or you could pass the event object and access the checkbox element through the event.target property:
For example:
<input type="checkbox" id="termsChkbx " onchange="isChecked(this, 'sub1')" />
Then you can access a reference to the checkbox element that fired on the change event:
function isChecked(checkbox, sub1) {
// checkbox
}
After changing a couple things, it would work as expected:
function isChecked(checkbox, sub1) {
var button = document.getElementById(sub1);
if (checkbox.checked === true) {
button.disabled = "";
} else {
button.disabled = "disabled";
}
}
However, you can simplify the code and rewrite it to:
Example Here
<input type="checkbox" id="termsChkbx " onchange="isChecked(this, 'sub1')" />
function isChecked(checkbox, sub1) {
document.getElementById(sub1).disabled = !checkbox.checked;
}
As a side note, I would highly suggest using unobtrusive JavaScript and add an event listener to the element in order to avoid inline onchange events:
Example Here
document.getElementById('termsChkbx').addEventListener('click', function (e) {
document.getElementById('sub1').disabled = !e.target.checked;
});
Here is the complete code
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx " onclick="change_button(this,'sub1')"/>
</p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
<script type = "text/javascript">
function change_button(checkbx,button_id) {
var btn = document.getElementById(button_id);
if (checkbx.checked == true) {
btn.disabled = "";
} else {
btn.disabled = "disabled";
}
}
</script>
Try like this
<input type="checkbox" id="termsChkbx " onchange="isChecked(this,'sub1')"/></p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
JS
function isChecked(chk,sub1) {
var myLayer = document.getElementById(sub1);
if (chk.checked == true) {
myLayer.disabled = false;
} else {
myLayer.disabled = true;
};
}
PLUNKR
The major problem can be easily checked by using the browser's debug console. There you can immediately see an exception.
Try this:
Html:
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="checked('sub1', this.checked);" />
</p>
<p>
<input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled" />
</p>
JavaScript:
function checked(sub1, checkedState) {
document.getElementById(sub1, this).disabled = !checkedState;
}
But be aware, that this code snippet is not best practice. It just solves your current problem without using libraries like jQuery.
Try using this JQuery function
$(function() {
$('#termsChkbx').click(function() {
if ($(this).is(':checked')) {
$('#sub1').removeAttr('disabled');
} else {
$('#sub1').attr('disabled', 'disabled');
}
});
});
Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" /></p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
<script>
$(function() {
$('#termsChkbx').click(function() {
if ($(this).is(':checked')) {
$('#sub1').removeAttr('disabled');
} else {
$('#sub1').attr('disabled', 'disabled');
}
});
});
</script>
While your problem has been solved, there is no need for JavaScript here.
This can be done with pure CSS/HTML:
input[type="checkbox"]:not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>
I've used the :not() pseudo-class to detect when a check-box isn't ticked as this is w3c's recommended approach. I wasn't sure where (in HTML) the check box is in relevance to the button, so I used the tilde (~ general sibling selector) to find the button. If the check-box is immediately before the button I would recommend using the adjacent sibling selector + instead.
However if you have multiple check-boxes and you only want one check-box to toggle the button's state then using the :nth-of-type pseudo class or an id may be more appropriate:
input[type="checkbox"]:nth-of-type(2):not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>
Otherwise all the check-boxes will be 'required' for the button to become click-able:
input[type="checkbox"]:not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>

Identify the value of clicked submit button with multiple submit buttons

I have situation where i need to track which submit button click in order to do set variables according to that. Below is the test code,
<script>
function submitForm(form) {
alert(document.getElementById('sb').value);
if (document.getElementById('sb').value=="One") {
//Do something
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
The alert always shows One even if i click button Two or Three. But the url change with clickable parameter. How to alert the value which is in the clickable submit button?
Note: I want a solution with out JQuery
EDIT: I change the code bit which the onsubmit call the submitForm(this);
The problem is even use document.forms[0].sb.value its undefined because document.forms[0].sb return a node list of all submit buttons as its same as with document.getElementById('sb')
Here is what I think is a simpler solution to this problem. It does not require any extra events.
<script>
function submitForm(form) {
console.log(document.activeElement.value);
if (document.activeElement.value == 'One') {
console.log("Have one.");
return false;
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
jsfiddle
What I would like an answer to is how the form is getting the query set to "?sb={value}".
I would suggest you to use buttons, instead of multiple submit buttons. In the onclick attribute of the buttons, submit the form using javascript.
You can try like this,
<form>
<input class="myButton" type="submit" name="sb" value="One">
<input class="myButton" type="submit" name="sb" value="Two">
<input class="myButton" type="submit" name="sb" value="Three">
</form>
<script type="text/javascript">
$(".myButton").on('click', function() {
alert($(this).val());
});
</script>
I'm a bit new to javascript; please forgive me if I'm wrong on this. Wouldn't it make a difference if your if statement had a 3rd = sign?
Should it be:
if (document.getElementById('sb').value === "One") {
//Do something
}
return true;
Continuing the answer above:
<script>
function m(value) {
alert(value);
}
</script>
<input type="button" value="One" onClick="m(this.value)">
<input type="button" value="Two" onClick="m(this.value)">
<input type="button" value="Three" onClick="m(this.value)">
You can of course see what's the id:
<input type="button" id='myId' value="Three" onClick="m(this.id)">
you can try with jquery something like :
$(":submit").live('click', function() {
alert($(this).val());
})
This is a non-jquery, simple solution for detecting which submit button was clicked.
<script>
function submitForm(form) {
console.log(document.getElementById('btn_clicked').value);
if (document.getElementById('btn_clicked').value === 'One') {
console.log("Have one.");
return false;
}
return true;
}
</script>
<form action="" method="get" onsubmit="return submitForm(this);" ;">
<input type="hidden" name="btn_clicked" id="btn_clicked" value="">
<input type="submit" name="sb" value="One" onclick="document.getElementById('btn_clicked').value='One';">
<input type="submit" name="sb" value="Two" onclick="document.getElementById('btn_clicked').value='Two';">
</form>

Simple JavaScript Checkbox Validation

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>​
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks

Append an input after a textarea with Javascript or jQuery

I have a textarea in a DIV that I can not modify.
I need to add an element, an input checkbox, just after the text area with javascript.
This is the code :
<div id="msgrapidosinick"><p class="msguser">My Wall</p>
<form method="post" id="messaggioajaxd" name="frm2">
<textarea class="areamsgnoava" name="messaggio"></textarea>
<input type="hidden" value="1" name="invia" id="invia">
<input type="hidden" value="1" name="riceve" id="riceve">
<input type="hidden" value="/assyrian" name="pagina" id="pagina">
<input type="submit" value="Share" class="submsg" name="senda2" style="display: none;">
</form>
</div>
So just after the textarea I need to add an element, that is a input checkbox, when the textarea is clicked.
How do I do that?
Please help me.
Just to let you know my site loads also jQuery 1.3.2
Thank you
You can use the aptly-named after() method:
$("textarea[name=messaggio]").click(function() {
$(this).after("<input type='checkbox' name='yourCheckBoxName' />");
});
If you want to avoid creating the check box if it already exists, you can do something like:
$("textarea[name=messaggio]").click(function() {
var $this = $(this);
if (!$this.next(":checkbox").length) {
$this.after("<input type='checkbox' name='yourCheckBoxName' />");
}
});
Presuming you only want the checkbox created on the first click to the textarea, you could do something like this:
$("#messaggioajaxd textarea").click(function(){
if ($('#createdCheckbox').length==0){
$('<input />').attr('type','checkbox').attr('id','createdCheckbox').insertAfter($(this));
}
});
Example on jsfiddle
Niklas beat me to it but here is what I was going to suggest...
Demo: http://jsfiddle.net/wdm954/ppnzf/1/
$('textarea.areamsgnoava').click(function() {
if ($('input.new').length == 0) {
$(this).after('<input type="checkbox" class="new" />');
}
});
I think that some IE version will not like that you add a field dynamically. If you can add an element to the form, may be you could change the form totally, and inject it as a new form instead, using div.innerHTML or using the DOM.
And add the checkbox in the original HTML as hidden, and show it if the textarea is clicked.
eg:
<div id="msgrapidosinick"><p class="msguser">My Wall</p>
<form method="post" id="messaggioajaxd" name="frm2">
<textarea class="areamsgnoava" name="messaggio"></textarea>
<input type="checkbox" name="checkBox" id="checkBox" style="display:none">
<input type="hidden" value="1" name="invia" id="invia">
<input type="hidden" value="1" name="riceve" id="riceve">
<input type="hidden" value="/assyrian" name="pagina" id="pagina">
<input type="submit" value="Share" class="submsg" name="senda2" style="display: none;">
</form>
</div>
Then if you have the reference of the textarea DOM node:
textarea.onfocus = function(ev){
var ta = ev.target || ev.srcElement;
ta.form.checkBox.removeAttribute('style');
}
Or using jQuery and focus.

validation not working still submitting the form

Now here is another problem..
my code:
<script type="text/javascript">
function validate_form ()
{
if ( document.myform.tele_caller.value == "" )
{
alert ( "Please insert the Name" );
return false;
}
else
{
return true;
}
}
</script>
and the form-
<form action="telecallerinfo.php?action=modify&id=<?php echo $id;?>" method="post" enctype="multipart/form-data" name="myform"
onsubmit="return validate_form ( );">
<table class="panel1">
<tr>
<td align="center">Caller Name:
<input name="tele_caller" type="text" size="15" value="<?php echo $tele_caller?>" /></td>
</tr>
<tr>
<td align="right">
<input name="submit" id="submit" type="image" src="images/submit.gif" width="60" onclick="this.form.submit();"/>
<img src="images/cancel.gif" height="25" width="70"/>
</td>
</tr>
</table>
</form>
now the validation is called and the alert box is also being displayed but the form is still being submitted. where is the mistake?
You're manually calling the submit() here:
onclick="this.form.submit();"
Just remove that onclick handler, there's no need for that handler, it'll happen automatically since it's inside the <form>.
Here's the comparison: your current code, with onclick (still submitting) vs. your code with onclick removed (only submitting when valid).
Remove onclick="this.form.submit(); from the input-submit tag.
Try to use input with type submit and no onclick event
<input type="submit" id="submit"/>
and you can put image in css
input#submit {
background-image: images/submit.gif;
width: 60px;
}

Categories