Require radio button html and javascript - javascript

I have the following html code
<input type="radio" name="months" value="TBI-6">
<input type="radio" name="months" value="UNI-6">
And i have this submitt button
$('#button-confirm').on('click', function() {
$.ajax({
type: 'post',
url: 'index.php?route=payment/zero_rate/confirm',
cache: false,
data:{
egn: $('#input-payment-egn').val(),
months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val()
},
beforeSend: function() {
$('#button-confirm').button('loading');
},
complete: function() {
$('#button-confirm').button('reset');
},
success: function() {
location = '<?php echo $continue; ?>';
}
});
});
How can i validate this two radio buttons? I dont want to let the user to submitt the form and leave the page without choosing one of the radio buttons?

$('input[name=months]:checked').length
should tell you how many radio buttons in the group are checked.
So verify that is above 0 before you continue with the form submission.

Check the radio button if checked
<input type="radio" name="months" value="TBI-6" class="radiobtn">
<button id="button-confirm">
Submit
</button>
$('#button-confirm').on('click', function() {
if($('.radiobtn').is(':checked')) { alert("it's checked");
$.ajax({
type: 'post',
url: 'index.php?route=payment/zero_rate/confirm',
cache: false,
data:{
egn: $('#input-payment-egn').val(),
months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val()
},
beforeSend: function() {
$('#button-confirm').button('loading');
},
complete: function() {
$('#button-confirm').button('reset');
},
success: function() {
location = '<?php echo $continue; ?>';
}
});
} else {
alert("it's not checked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="months" value="TBI-6" class="radiobtn">
<button id="button-confirm">
Submit
</button>

Related

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

Unable to submit the ajax form multiple times after using .submit() function

This is my code:
var onloadCallback = function() {
$( "#submit" ).each(function() {
grecaptcha.render($( this ).attr('id'), {
'sitekey' : '6Lcjvi4UAAAAAIR7_ckItF2HfMEFHx427WUDdGDk',
'callback' : onsubmitforgotpass
});
});
};
function onsubmitforgotpass(token) {
$(document).ready(function() {
$("form.formajax").submit(function() {
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
return false;
});
$("form.formajax").submit();
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="" method="post" class="formajax">
<input type="text">
<input type="submit" id="submit">
</form>
I am unable to submit this ajax form multiple times.
It is probably because of these 2 lines:
$("form.formajax").submit(function()
and
$("form.formajax").submit();
If I replace those line with $("#submit").click(function() and $("#submit").click();
Then I can submit the form multiple times.
Anyway to submit the form multiple times using .submit(); function? (It will help me in some other part of my code also, so I do not want to use click();
hey please test the following things:
Please remove the actions
action="abc.com"
to
action=""
add ajax call on button click like below example:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
});
});

Send multiple checkbox data with ajax

I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});

How to combine toggle on off with http.get

I try make toggle with bootstrap toggle and give som function http.get if toggle click on or off. But i have some trouble if on clicked it work but if off clicked it didn't work. My code like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=rlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Lock');
}
});
}).off('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=runlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Unlock');
}
});
});
});
</script>
i don't know how to fix it, please helpme to solve my problem
You can try something like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
var Checked_or_not = this.checked, // check if checked or unchecked
tN = Checked_or_not ? 'rlock' : 'runlock'; // if checked return 'rlock' if unchecked return 'runlock' for tN in url
$.ajax({
url: 'http://localhost/web.php?tN='+ tN +'&f12=123456789', // add tN in url
data: { checked: Checked_or_not },
success: function() {
console.log('Lock');
}
});
});
});
</script>

Ajax call on checking a checkbox

I am having a two checkboxes.Now on click of one of the checkbox I want to make an ajax call to a jsp page.That jsp page is to show a table that contains datat being fetched from database.
Now,The problem is say i have two checkboxes like :
<div class="search-inputs">
<input class="searchName" type="text" placeholder="Search Here.."></input>
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<input class="searchDateFrom" type="text" placeholder="Search From"></input>
<input class="searchDateTo" type="text" placeholder="Search To"></input>
<input class="Datesubmit" type="button" value="Search"></input>
<div id="container"></div>
How to do it ?Please help
My Script part :
$(document).ready(function () {
$('.search-select').on('change', function(){
$('.search-inputs').children().hide();
var classn =$(this).find(":selected").val();
//alert(classn);
if(classn=='searchName')
{
//alert("searchname");
$('.'+"searchName").show();
}
else if(classn=='searchType')
{
//alert("searchType");
$('.'+"searchType1").show();
$('.'+"searchtype1label").show();
$('.'+"searchType2").show();
$('.'+"searchtype2label").show();
}
else if(classn=='searchDate'){
//alert("searchType");
$('.'+"searchDateFrom").show();
$('.'+"searchDateTo").show();
$('.'+"Datesubmit").show();
}
});
$('#emailNotification').on('change',function() {
//var checked = $(this).is(':checked');
if(this.checked){
//alert("in");
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata: "emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
});
But how to show the table on the same page ?
you have to change your html slightly with this--
give same class name to both check boxes.
<input class="searchType" type="checkbox" name="emailNotification" id="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType" type="checkbox" name="SharingNotification" id="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
Now slightly change in jquery part--
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "POST",
url: 'searchOnType.jsp',
data: $(this).attr('id'), //--> send id of checked checkbox on other page
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
you have to use change event for this like below:
Html:
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<div id="container">
</div>
JQuery:
$('#emailNotification').on('change',function() {
if(this.checked){
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata:"emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

Categories

Resources