I'm getting undefined output from my jQuery function below. I initially assigned empty string to my product_type, I want it to be empty when I don't choose anyone of them, but still getting undefined output. Hopefully, I can have some hints here.
$(function () {
var internal_note = {};
var customer_note = {};
var product_type = "";
var web_camera = "";
var touch_screen = "";
$( "#test" ).on("click" , 'button:not(:disabled)',function(event){
if ($('input[name="product_type"]:checked')){
product_type = $('input[name="product_type"]:checked').attr("value");
};
if($('input[name="web_camera"]:checked')){
web_camera = $('input[name="web_camera"]:checked').attr("value");
};
if($('input[name="touch_screen"]:checked')){
touch_screen = $('input[name="touch_screen"]:checked').attr("value");
};
$('#left_note_list input').each(function(){
internal_note[this.value] = JSON.stringify($(this).val());
});
alert(product_type);
$.ajax({
type: "post",
url: '/insert/',
data: {
'internal_note': JSON.stringify(internal_note),
'product_type': JSON.stringify(product_type),
'web_camera': JSON.stringify(web_camera),
'touch_screen': JSON.stringify(touch_screen)
},
success: function (data) {
swal(data,'You Click the Button','success');
$("#test button:not(:disabled)").text('Done!').attr('disabled', 'disabled');
},
error: function(data){
swal(data.responseText,'You Click the Button', 'error');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-md-4">
<h4 class="sub-header" id="product_type">Product Type</h4>
<form>
<div class="radio"><label><input type="radio" name="product_type" value="Laptop">Laptop</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Tower">Tower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Minitower">Minitower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Small Form Factor">Small Form Factor</label></div>
</form>
</div><!-- /.col-lg-4 Product Type-->
<div class="text-center" id="test">
<button target="_blank"
class="btn btn-primary ">
Test
</button>
</div>
Your issue is coming from the way you are checking to see is the checkbox is checked. This if check if ($('input[name="product_type"]:checked')). This works, but you do not get a true or false answer back, so you are essentially checking truthy instead. You can either check the length of $('input[name="product_type"]:checked') or you can do this instead
$('input[name="product_type"]').is(":checked")
Here is a good post on how to check whether or not a checkbox is checked
jQuery if checkbox is checked
$(function () {
var internal_note = {};
var customer_note = {};
var product_type = "";
var web_camera = "";
var touch_screen = "";
$( "#test" ).on("click" , 'button:not(:disabled)',function(event){
if ($('input[name="product_type"]').is(":checked")){
product_type = $('input[name="product_type"]:checked').attr("value");
}
if($('input[name="web_camera"]:checked')){
web_camera = $('input[name="web_camera"]:checked').attr("value");
}
if($('input[name="touch_screen"]:checked')){
touch_screen = $('input[name="touch_screen"]:checked').attr("value");
}
$('#left_note_list input').each(function(){
internal_note[this.value] = JSON.stringify($(this).val());
});
alert(product_type);
$.ajax({
type: "post",
url: '/insert/',
data: {
'internal_note': JSON.stringify(internal_note),
'product_type': JSON.stringify(product_type),
'web_camera': JSON.stringify(web_camera),
'touch_screen': JSON.stringify(touch_screen)
},
success: function (data) {
swal(data,'You Click the Button','success');
$("#test button:not(:disabled)").text('Done!').attr('disabled', 'disabled');
},
error: function(data){
swal(data.responseText,'You Click the Button', 'error');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-md-4">
<h4 class="sub-header" id="product_type">Product Type</h4>
<form>
<div class="radio"><label><input type="radio" name="product_type" value="Laptop">Laptop</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Tower">Tower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Minitower">Minitower</label></div>
<div class="radio"><label><input type="radio" name="product_type" value="Small Form Factor">Small Form Factor</label></div>
</form>
</div><!-- /.col-lg-4 Product Type-->
<div class="text-center" id="test">
<button target="_blank"
class="btn btn-primary ">
Test
</button>
</div>
It's because your conditional check is never returning false, so it's always assigning the value of product_type, even when nothing is selected. Instead of the check you have, use this:
if ($('input[name="product_type"]:checked').length>0){ ... }
That'll correctly check to ensure you have a checked product type.
Related
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.
});
I have text box(for live search) and whenever i enter more than 3 characters then
result is showing (from database) via ajax response as checkboxes with name, I just want whenever user
select any checkbox so this checkbox should display in div so user can search multiple data and can see
selected checkboxes,How can i do this ?
Right now Here is my html code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/">
<h1>Newsletter Form</h1>
<p class="question">Newsletter Type?</p>
<div class="question-answer">
<label><input type="radio" value="Delas" name="DealType" /> Deals</label>
<label><input type="radio" value="PremiumDeals" name="DealType" /> Premium Deals</label>
</div>
<div id="deals-section" style="display:none;">
<p class="question">Add Merchant Name</p>
<div class="question-answer">
<input type="text" name="merchantname" id="merchantname" value="">
</div>
<div id="suggestions">
<div id="suggestionslist">
</div>
</div>
<img id="loading-image" src="<?php echo base_url(); ?>/assets/images/ajax-loader.gif" style="display:none;"/>
<table id="fees_table">
</table>
<div class="form-group">
<label class="control-label col-xs-3"></label>
<div class="col-xs-8">
<ul id="sparepartList" style="list-style-type: none; padding: 0;"></ul>
</div>
</div>
<div class="btn-block" id="send" >
<button type="submit" href="/">Send</button>
</div>
</div>
</form>
Here is my script which showing "MerchantName"(data from database) with "checkbox",i just want whenever we click on any
checkbox this "Merchant Data" should display in seprate div/belowcheckbox, How can i do this ?
<script>
$('#merchantname').keyup(function() {
var merchantname = $(this).val();
if(merchantname.length>= 3){
$.ajax({
type: 'POST',
url: "<?php echo base_url('Newsletter/GetMerchantName');?>",
cache : false,
data: {'merchantname': merchantname},
dataType: "json",
async: false,
beforeSend: function() {
$("#loading-image").show();
},
success: function(response) {
$('#sparepartList').empty();
$.each(response, function(key,value)
{
let li = $('<li><input type="checkbox" name="merchantName[]" value="' + value.merchantName + '" />' +
'<input type="text" name="sparepart" value="' + value.merchantName + '" /></li>');
$('#sparepartList').append(li);
});
$("#loading-image").hide();
},
error: function(response) {
console.log(response);
}
})
return false;
}
});
</script>
You can get the checkbox value on checked with jquery.
$('input[type=checkbox]').on('change', function() {
var val = this.checked ? this.value : '';
$('#showDiv').html(val);
});
I am creating a small application for the examination, when I click the next button, the current answer radio button value should be stored in some variable and that value should be added to the next answer value, i am doing this with the jquery, but my stored value is always re-setting to zero when I call that function for the multiple times,
here is what I tried so far.
following is my view page
<div>
<div id="questionvalue">#a.QDescription</div>
<div>
<div id="questionvalue">
<input type="radio" name="test" value="#a.Choice1Percent"> #a.Choice1Desc<br>
</div>
</div>
<div>
<input type="radio" name="test" value="#a.Choice2Percent"> #a.Choice2Desc<br>
</div>
<div>
<input type="radio" name="test" value="#a.Choice3Percent"> #a.Choice3Desc<br>
</div>
<div>
<input type="radio" name="test" value="#a.Choice4Percent"> #a.Choice4Desc<br>
</div>
<button type="button" id="starttestbuttonid" class="btn btn-default" onclick="StartTest()">Next</button>
following is the script which i am trying to add the sum of the answers
<script>
function StartTest() {
debugger;
var selopt = parseFloat($('input[name=test]:checked').val());
var optionssum=0;
optionssum+= optionssum + selopt;
$.ajax({
url: $("baseUrl").html() + "Test/_QuestionView",
type: "POST",
data: { selectedoption: selopt},
success: function (data) {
debugger;
$('#appendquestion').html(data);
// $('#myModal').modal(show);
},
error: function (data) {
$('#loading').hide();
}
});
}
can anyone help in how to calculate the sum.
You can't do optionssum += optionssum + selopt; I think you mean optionssum += selopt;
Also, of course optionssum is going to be reset every time, you have it right here var optionssum=0; inside of StartTest() and every time the button is clicked that is called.
Just change your code to this, it should work (Made it a global variable)
var optionssum=0;
function StartTest() {
debugger;
var selopt = parseFloat($('input[name=test]:checked').val());
optionssum+= selopt;
$.ajax({
url: $("baseUrl").html() + "Test/_QuestionView",
type: "POST",
data: { selectedoption: selopt},
success: function (data) {
debugger;
$('#appendquestion').html(data);
// $('#myModal').modal(show);
},
error: function (data) {
$('#loading').hide();
}
});
}
The problem is because you keep set var optionssum=0;
I can suggest to you doing something like below
HTML
<div id="questionvalue">#a.QDescription</div>
<div>
<div id="questionvalue">
<input type="radio" name="test" value="1"> 1<br>
</div>
</div>
<div>
<input type="radio" name="test" value="2"> 2<br>
</div>
<div>
<input type="radio" name="test" value="3"> 3<br>
</div>
<div>
<input type="radio" name="test" value="4"> 4<br>
</div>
<button type="button" id="starttestbuttonid" class="btn btn-default" data-optionssum="0" >Next</button>
<br>
<b>Total : <span class="tot" >
</span>
</b>
JAVASCRIPT
$(document).ready(function(){
$("#starttestbuttonid").on("click",function(){
var optionssum = $(this).data("optionssum");
var selopt = parseFloat($('input[name=test]:checked').val());
alert("+ "+selopt);
if(!isNaN(selopt))
optionssum+= selopt;
/*
Your ajax
*/
//set latest total value
$(this).data("optionssum",optionssum);
// just want to show the value
$(".tot").html(optionssum);
});
});
JSFiddle example : https://jsfiddle.net/synz/Ltv3k0bq/
<script>
$('input[type="checkbox"]').on('change', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = {},
fdata = [],
loc = $('<a>', {href:window.location})[0];
$('input[tpye="checkbox"]').each(function(i){
if(this.checked){
if(!data.hasOwnProperty(this.name)){
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
fdata = fdata.join('&');
$.post('/wines/all-wines/', fdata);
console.log(fdata);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+fdata);
}
});
<div class="panel-body">
<div class="rowElem">
<input type="checkbox" name="country" value="1" id="">
<label>Color #1</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="2" id="">
<label>Color #2</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="3" id="">
<label>Color #3</label>
</div>
</div>
I'm using laravel thats why i'm passing X-CSRF token. What i want to achieve is when user clicks on one or more checkboxes it automatically change url to something like this : link.com/products/all-products?country=1,2,3,4,5
but after clicking on checkboxes it only change url to : link.com/products/all-products? and thats mainly it. What could be wrong in the code? Thank you very much!
In addition to what nbkHope pointed out you need the following:
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
var countryArr = fdata["country"];
fdata = countryArr.join('&');
Your array looks like this: {country: Array()}, so you need to get country out of fdata and then call join.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
I'm unable to get a basic if statement inside a jquery $.each loop working. I have a json object that I loop through, and if the value entered in a text box is found in the json object, I return a flag I set as false. But for some reason, the if statement is not executing. Here is the code:
var authorlist = [
{"AUTHOR":"DONNA EDWARDS","COUNTRY":"USA","REGION":"MIDWEST"},
{"AUTHOR":"EMERALD JONES","COUNTRY":"UK","REGION":"EU"},
{"AUTHOR":"SHAKESPEARE","COUNTRY":"UK","REGION":"EU"}];
function checkName() {
var nameIsValid = true;
var nametocheck = $("#name").val();
$.each(authorlist, function(index, val){
//console.log(val.AUTHOR);
if(nametocheck == val.AUTHOR) {
//console.log(val.AUTHOR);
nameIsValid = false;
return false;
}
});
return nameIsValid;
}
$("#btnCheck").on("click", function(){
console.log("The name entered is valid: " + checkName());
});
<form class="form-horizontal" name="paymentInformation" id="paymentInformation" action="verifyOrder.cfm" method="post" role="form">
<div class="form-group">
<fieldset class="col-sm-12">
<!-- Row 1 -->
<div class="row">
<div class="col-sm-6">
<label for="id2" class="col-6 col-form-label">
Book Name
</label>
<input type="form-control" placeholder="Book Name" type="text" id="id2" name="id2" class="col-10">
<button type="button" class="btn btn-primary" id="btnCheck">Check</button>
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
https://jsfiddle.net/wqnkz4v7/
Edit following
var nametocheck = $("#id2").val();
or Use following
$("input[name='name']").val();
You need to address the right id.
var nametocheck = $("#id2").val();
// ^^^^
The error you have is in var nametocheck = $("#name").val();.
The selector according to the html should be "#id2".