Prevent Default Enter on Form - javascript

My form contain about 10 input text boxes ,The problem is when I press the enter key from a input text box it's directly going to submit button by skipping the text boxes between them.I added my snippet below.it's working fine when using mouse
function getElement(elm){
var elem = document.getElementById(elm);
return elem;
}
function sendData(){
getElement('submit-button').addEventListener("click",function(){
getElement("success-txt").removeClass('display-none');
if(getElement('pbarcode')){
var pbarcode = $('#pbarcode').val();
var pname = $('#pname').val();
var pprice = $('#pprice').val();
var poprice = $('#poprice').val();
$.ajax({
url:'getdata.php',
method:"post",
data:{pbarcode:pbarcode,pname:pname,pprice:pprice,poprice:poprice},
cache: false,
onSuccess: function(response){
alert('success');
},
onFailure: function(response){
alert('failure');
}
});
}
else{
alert("error");
}
});
}
function showWarnMessage(){
getElement("submit-button").addEventListener("click",function(){
alert("you enteres submitt button");
var data1 = $('#pbarcode').val();
var data2 = $('#pname').val();
var data3 = $('#pprice').val();
var l3 = data3.length;
var l1 = data1.length;
var l2 = data2.length;
var flag = 0;
if(l1 < 1){
flag = 1;
}
if(l2 < 1){
flag = 1;
}
if(l3 < 1){
flag = 1;
}
alert(flag);
if (flag == '0'){
alert(flag + "go");
sendData();
}
});
}
showWarnMessage();
ul,li {
list-style : none;
padding :0px;
margin : 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="create-user" method="post">
<ul id="create-new-user-page">
<li>
<span>Product Barcode</span>
<input type="number" id="pbarcode" name="barcode" class="form-data" required>
</li>
<li>
<span>Product Name</span>
<input type="text" class="form-data" name="pname" id="pname" required>
</li>
<li>
<span>Product Price</span>
<input type="number" class="form-data" name="pprice" id="pprice" required>
</li>
<li>
<input type="submit" id="submit-button" Value="Submit" name="submit_data">
</li>
</ul>
</form>
What I have been tried so far is using
event.preventDefault();
on 'enter' click on text box ,I added the codes below
function preventDefault(elem){
getElement('elem').addEventListener('keypress',function(){
if (event.keyCode == 13) {
event.preventDefault();
alert('calling ')
}
});
}
preventDefault('pname');
preventDefault('pprice');
preventDefault('pname');
preventDefault('pbarcode');
but which also returns the same result.I would like to have a form which works fine with the enter key.(ie,when I press 'enter' key from one input text box which should move in to the next text box ,instead moving directly in to the form submit button)

you can change the button type submit to button.
<input type="button" id="submit-button" Value="Submit" name="submit_data">

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

How to change the value of a previous check box that has been selected in JQuery?

Here is what I'm trying to do.
I have the ability to create a form when there is an option to create one in Javascript.
Here is an option to add an address:
<i class="fas fa-plus-circle"></i> <span class="newUrlText">add new address
Here is the form in question:
<input type="text" class="form-control" id="new-address-1-%ID%" name="new-address-1-%ID%" placeholder="Address Line 1">
<input type="text" class="form-control" id="new-address-2-%ID%" name="new-address-2-%ID%"
placeholder="Address Line 2">
<label for="message" class="control-label"><span class="billable-text"><?php _e('Primary Address'); ?></span></label>
<label class="switch" for="primary-%ID%" style="margin-left: 10px;top: 10px;">
<input type="checkbox" class="primary-%ID%" name="primary-%ID%" id="primary-%ID%" />
<div class="slider round gray"></div>
</label>
Here is the javascript that generates the form:
<script language="javascript">
var newAddressIndex = 1;
var addressarray = [];
function addNewAddress() {
var container = getElement("addressContainer");
addressarray.push(newAddressIndex);
var htmlAddress = '<?php echo addslashes(App_String::stripBreaksTabsMultipleWhitespace($newAddress)); ?>';
htmlAddress = htmlAddress.replace(/%ID%/g, newAddressIndex);
var node = document.createElement("div");
node.innerHTML = htmlAddress;
container.appendChild(node);
$('#newAddressCount_'+newAssetIndex).val(newAssetIndex);
++newAddressIndex;
test(addressarray);
}
What I'm trying to do is the following:
If the user selects the checkbox and then decides to select the next checkbox, I would like to change the previous checkbox from selected to no selected.
How would I go about doing that?
Thank you
I found a solution:
What I did was, that I created a function to get the current value of the checkboxes like this:
getAddrValue(addressarray);
Then within the function the follwoing:
function getAddrValue (addressarray) {
$('#primary-'+index).change(function() {
var checked = this.checked ? 1 : 0;
prevCheckbox = index-1;
if (checked == 1) {
if (document.getElementById('primary-'+prevCheckbox) !== null ) {
let inputs = document.getElementById('primary-'+prevCheckbox);
inputs.checked = false;
}
}
});
}

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

JQuery click and submit not firing, while change does

I have a dynamic DOM with add and save button to add a new elements and to save all the data in DOM elements, respectively. Meanwhile each row has its own remove button to remove the corresponding line.
When user log in to the system, she will be redirected to homepage by controller. (I am using codeigniter framework for PHP). This controller will pass all the session and another data to populate user's home page including the DOM data that I mentioned in the previous paragraph.
So I have two different forms in the same page. Here is the first form
<form class="frm_GP" name="frm_GP" id="frm_GP" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/users/save_preference" method="post">
<div class="table" id="preference_GP">
<?php echo $userGP_html ?>
</div>
<div class="tr">
<div class="td">
<input class="button" type="button" name="btn_Add_GP" id="btn_Add_GP" value="Add category" />
</div>
<div class="td">
<input class="button" type="submit" name="btn_Save_GP" id="btn_Save_GP" value="Save" />
</div>
</div>
<input type="hidden" id="formName" name="formName" value="GP" />
<!--<input type="hidden" id="Dropdown_GP" name="Dropdown_GP" value="<?php echo $Dropdown_GP;?>" />-->
</form>
and the second one
<form class="frm_GP" name="frm_GP" id="frm_GP" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/users/save_preference" method="post">
<div class="table" id="preference_GP">
<?php echo $userGP_html ?>
</div>
<div class="tr">
<div class="td">
<input class="button" type="button" name="btn_Add_GP" id="btn_Add_GP" value="Add category" />
</div>
<div class="td">
<input class="button" type="submit" name="btn_Save_GP" id="btn_Save_GP" value="Save" />
</div>
</div>
<input type="hidden" id="formName" name="formName" value="GP" />
<!--<input type="hidden" id="Dropdown_GP" name="Dropdown_GP" value="<?php echo $Dropdown_GP;?>" />-->
</form>
And here is my jQuery codes :
<script type="text/javascript">
jQuery(document).ready(function(){
var fileId = 0;
var wrapperGP = jQuery("#preference_GP");
var wrapperCP = jQuery("#preference_CP");
var logout_button = jQuery("#btn_Logout");
var x = 0;
jQuery('.datepicker').datepicker({
minDate: new Date()
});
jQuery('[name^=frm_]').on('submit', '[name*="btn_Save"]', (function(e){
alert('aa');
var elementID = jQuery(this).closest('[name^=frm_]').attr('id');
var preference = jQuery.fn.getPreference(elementID);
var len = jQuery('.selCat'+preference).length;
var selCat = jQuery('.selCat'+preference);
var selSubCat = jQuery('.selSubCat'+preference);
var score = jQuery('.score');
var valid_score = ["10","20","30","40","50","60","70","80","90","100"];
for(i=0;i<len;i++){
var j = eval(i+1);
alert(jQuery(score).eq(i));
if(jQuery(selCat).eq(i).val()==='0'){
jQuery(selCat).get(i).focus();
jQuery('[name=error'+preference+']').html('Please select the category of row '+ j);
return false;
}
if(jQuery(selSubCat).eq(i).val()==='0'){
jQuery(selSubCat).get(i).focus();
jQuery('[name=error'+preference+']').html('Please select the sub category of row '+ j)
return false;
}
if(jQuery(score).eq(i).val()==='0' || jQuery(score).eq(i).val()==0 || jQuery(score).eq(i).val()===''){
jQuery(score).get(i).focus();
jQuery('[name=error'+preference+']').html('Please fill the score of row '+ j)
return false;
}
if(valid_score.indexOf(jQuery(score).eq(i).val())<0){
//jQuery(score).get(i).focus();
jQuery('[name=error'+preference+']').html('Please fill with the valid score at row '+ j)
return false;
}
}
//jQuery( "#frm"+preference ).submit();
return false;
}));
jQuery.fn.getPreference = function(elementID) {
var index = elementID.lastIndexOf('_');
var preference = elementID.substr(index,elementID.length);
return preference;
}
jQuery('[name^=frm_]').on('click', '[name*="btn_Add"]', (function(e){
alert('this');
/*
var elementID = jQuery(this).attr('id');
var preference = jQuery.fn.getPreference(elementID);
alert('this');
var dropdown = jQuery(".Dropdown"+preference).val();
e.preventDefault();
x++;
if(preference==="_GP"){
jQuery('#preference'+preference).append(dropdown);
}else{
jQuery('#preference'+preference).append(dropdown);
}
*/
/*
$.post('<?php echo base_url();?>'+'index.php/client/ajax_cat',{preference:preference}, function(returned){
jQuery('#preference'+preference).append(returned);
jQuery("[name*='selCat']").change(function(){
var elementID = jQuery(this).attr('class');
var preference = jQuery.fn.getPreference(elementID);
var index = jQuery(this).index('.selCat'+preference);
var value = jQuery(this).val();
var selSubCat = (".selSubCat"+preference);
jQuery('[name=error'+preference+']').html('');
$.post('<?php echo base_url();?>'+'index.php/client/ajax_subcat',{id:value}, function(returned){
jQuery(selSubCat+":eq("+index+")").html(returned);
});
});
});
*/
return false;
}));
jQuery("[name*='selCat']").change(function(){
var elementID = jQuery(this).attr('class');
var preference = jQuery.fn.getPreference(elementID);
var index = jQuery(this).index('.selCat'+preference);
var value = jQuery(this).val();
var selSubCat = (".selSubCat"+preference);
jQuery('[name=error'+preference+']').html('');
$.post('<?php echo base_url();?>'+'index.php/client/ajax_subcat',{id:value}, function(returned){
jQuery(selSubCat+":eq("+index+")").html(returned);
});
return false;
});
jQuery(wrapperGP).on("click","#btnRemove", function(e){
e.preventDefault();
jQuery(this).closest(".tr").remove();
x--;
return false;
});
jQuery(wrapperCP).on("click","#btnRemove", function(e){
e.preventDefault();
jQuery(this).closest(".tr").remove();
x--;
return false;
});
});
</script>
Any idea why the submit, click and change functions are not firing? meanwhile the remove is working ?
After few tries, changing the naming in jquery it finally works now.
I change from this
jQuery('[name^=frm_]').on('submit', '[name*="btn_Save"]', (function(e){
//code here
});
to
jQuery('[name*=frm_]').on('click', '[name*=btn_Save]', (function(e){
//code here
});
name^=frm_ is not working. it's supposed to find all the elements that have name begin with frm_. Replaced the ^ with * which is to find the elements that contain frm_ as a name.
And also, I guess there is no submit as a parameter in jQuery's event listener even though the type of the input is a submit not a button.
and I did the same thing for the "btn_Add" on click

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

Categories