Radiobuttons and Checkboxes "checked" issue in Javascript - javascript

I have Javascript code using JQuery to create quizzes containing free text, radio buttons (single choice) and check boxes (multiple choice) questions. The quizzes are made using a web interface, with Zurb - Foundation for the style, and are being serialized in JSON. While creating the radio buttons and the check boxes answers for an specific question, when an user checks either component (to mark it as the valid answer, for example), it's supposed to validate this, and come as "true" (represented by the number "1") in the JSON.
It's currently working for the text type question, as it is basically hard-coded. But it's not doing the trick for the other two.
Here's the main pieces of code (If more is needed I'll edit the question): Whole quiz
storeQuiz: function( event ) {
var self = event.data;
var store = [];
$(self.element).find( '.question-content' ).each( function(){
var question = $( this );
var entry = { options: [] };
if ( question.parent().attr( 'class' ).match( /template/ ) ) {
return true;
}
entry['content'] = question.find( '.input' ).val();
entry['type'] = question.parent().attr( 'class' ).match( /quiz-(\w+)/ )[1];
question.find( '.option' ).each( function() {
var option = $( this );
var data = {};
if ( entry.type === 'text' ) {
data['valid'] = true;
} else {
data['valid'] = !!option.find( '.option-validation input' ).attr( 'checked' );
}
data['content'] = option.find( '.option-content textarea' ).val();
entry.options.push( data );
})
store.push( entry );
});
self.storeUpdate( store );
},
Radios:
buildRadios: function( data ) {
var tmpl = this.radiosHandler( {data: this} );
var self = this;
tmpl.find( '.option' ).remove();
tmpl.find( '.input' ).val( data.content );
$.each( data.options, function() {
var plus = tmpl.find( '.add' );
var option = self.addAnswer.call( plus, {data: self} );
option.find( '.option-validation input' ).attr( 'checked', this.valid );
option.find( '.option-content textarea' ).val( this.content );
});
},
Check boxes:
buildCheckboxes: function( data ) {
var tmpl = this.checkboxesHandler( {data: this} );
var self = this;
tmpl.find( '.option' ).remove();
tmpl.find( '.input' ).val( data.content );
$.each( data.options, function() {
var plus = tmpl.find( '.add' );
var option = self.addAnswer.call( plus, {data: self} );
option.find( '.option-validation input' ).attr( 'checked', this.valid );
option.find( '.option-content textarea' ).val( this.content );
});
},

its smarter if you use
$('input[type="checkbox"]').is(':checked');
return value is boolean

Do not use attr() when looking for checked values because it is actually a property so .prop() should be used.
if($('input[type="checkbox"]').prop('checked') === true)
{
// checkbox is checked, uncheck it
$('input[type="checkbox"]').prop('checked', false);
}
else
{
// checkbox is unchecked, check it
$('input[type="checkbox"]').prop('checked', true);
}
If you want to get fancy:
$('input[type="checkbox"]').on('change', function(){
if($(this).prop('checked')){
alert('TRUE : checked');
}
else{
alert('FALSE : unchecked');
}
});
This is the reason that <input type="checkbox" checked> works without needing to do <input type="checkbox" checked="checked">
When you check a checkbox with your mouse then the DOM object's property is set to Boolean TRUE and unchecking switches it to Boolean FALSE

There is another easy way ..
if($('inputSelector')[0].checked == true) {
}
to set the checkbox use
$('inputSelector')[0].checked = true / false;

I solved my problem thanks to a friend with this fix:
data['valid'] = !!option.find( '.option-validation input' ).attr( 'checked' );
Changed to:
data['valid'] = option.find( '.option-validation input' ).is( ':checked' );

Related

sum of two changing variables not totally correctly using Jquery

It is easier to see my codepen link: https://codepen.io/ScottFSchmidt/pen/GPWvQP Everything works, but the total of the total of the two variables are not adding up.
Failed attempts. There were 4 major failed attempts that I had (I tried other stuff too). I am wondering if I need to use eval.
$total.text(pizzaPrice.innerHTML+sodaPrice.innerHTML); //returns NAN
$total.text( $sodaTotal + $pizzaTotal); //returns 6 at ALL times, adding one pizza and one soda.
$total.text( $sodaTotal.val + $pizzaTotal.val ); //function (e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&
function sum($pizzaTotal, $sodaTotal) {
$sodaTotal+$pizzaTotal.html($total);
} //won't trigger with sum() but probably not the easiest way.
`
Full Code:
commented stuff out is stuff that did not work:
<script text=type/javascript>
$(document).ready(function(){
var $pizzaOptions = $( '.pizza-options' );
var pizzaPrice = $pizzaOptions.data( 'price' );
var $sodaOptions = $( '.soda-options' );
var sodaPrice = $sodaOptions.data( 'price' );
var $pizzaTotal = $( '.pizza-total' );
var $sodaTotal = $( '.soda-total' );
var $total = $( '.total' );
$total.text(pizzaPrice+sodaPrice);
// $total.text( $sodaTotal.val + $pizzaTotal.val );
function sum($pizzaTotal, $sodaTotal) {
$sodaTotal+$pizzaTotal.html($total);
}
function calculator( $totalEl, price, $options ) {
return function ( e ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length );
};
//$sum=$sum+$totalEl;
//$total.text($sum)
//sum();
}
$pizzaOptions.on( 'click', calculator( $pizzaTotal, pizzaPrice, $pizzaOptions ) );
//$pizzaOptions.on( 'click', sum($pizzaTotal, $sodaTotal);
//// $pizzaOptions.on( 'click', sum();
$sodaOptions.on( 'click', calculator( $sodaTotal, sodaPrice, $sodaOptions ) );
}); //end ready
</script>
Almost every suggested article is using SQL not Jquery. Most of the failed attempt ideas were from suggested articles. Thanks in advance.
Your sum function was never called, and it isn't completely correct.
Change sum to:
function sum() {
$total.text(Number($pizzaTotal.text())+Number($sodaTotal.text()));
}
Here we set the text of $total to $pizzaTotal + $sodaTotal. It would be a lot better to use variable instead of doing it this way.
Change calculator to:
function calculator( $totalEl, price, $options ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length );
}
Now the function will set the text instead of just returning another function.
Lastly change your click listeners to use an anonymous function, calling both calculator and sum:
$pizzaOptions.on( 'click', function() {
calculator( $pizzaTotal, pizzaPrice, $pizzaOptions );
sum();
});
$sodaOptions.on( 'click', function() {
calculator( $sodaTotal, sodaPrice, $sodaOptions );
sum();
});
Now they will also call sum when they're executed.
Here it is all together https://codepen.io/anon/pen/ZVexyP
codepen.io/ScottFSchmidt/pen/GPWvQP?editors=1010
Here is the full length solution:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="order-form">
<div class="pizza-options" data-price="5">
<h2>Pizza</h2>
<label>
<input type="checkbox" value="sausage"> Sausage
</label>
<label>
<input type="checkbox" value="pepperoni" data-price=".5"> Pepperoni
</label>
<label>
<input type="checkbox" value="mushrooms"> Mushrooms
</label>
</div>
<div class="soda-options" data-price="2">
<h2>Soda</h2>
<label>
<input type="checkbox" value="coke"> Coke
</label>
<label>
<input type="checkbox" value="pepsi"> Pepsi
</label>
</div>
<div class="totals">
<p>
<strong>Pizza Total:</strong> <span class="pizza-total"></span>
</p>
<p>
<strong>Soda Total:</strong> <span class="soda-total"></span>
</p>
<p>
<strong>Sub Total:</strong> <span class="subtotal"></span>
</p>
</div>
</form>
Javascript:
var $pizzaOptions = $( '.pizza-options' );
var pizzaPrice = +$pizzaOptions.data( 'price' );
var $sodaOptions = $( '.soda-options' );
var sodaPrice = +$sodaOptions.data( 'price' );
var $pizzaTotal = $( '.pizza-total' );
var $sodaTotal = $( '.soda-total' );
var $total = $( '.subtotal' );
function calculator( $totalEl, price, $options ) {
$totalEl.text( price * $options.find( '[type="checkbox"]:checked' ).length);
}
function sum() {
$total.text(Number($pizzaTotal.text())+Number($sodaTotal.text()));
}
$pizzaOptions.on( 'click', function() {
calculator( $pizzaTotal, pizzaPrice, $pizzaOptions );
sum();
});
$sodaOptions.on( 'click', function() {
calculator( $sodaTotal, sodaPrice, $sodaOptions );
sum();
});

Bootstrap datatables search input won't change

Im using bootstrap datatables, and im having a search input and whatever I do it won't remove Search text and add placeholder. I've seen examples here on stack and google but that didnt helped.
I believe this is the js for the search input:
function _fnFeatureHtmlFilter ( settings )
{
var classes = settings.oClasses;
var tableId = settings.sTableId;
var language = settings.oLanguage;
var previousSearch = settings.oPreviousSearch;
var features = settings.aanFeatures;
var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
var str = language.sSearch;
str = str.match(/_INPUT_/) ?
str.replace('_INPUT_', input) :
str+input;
var filter = $('<div/>', {
'id': ! features.f ? tableId+'_filter' : null,
'class': classes.sFilter
} )
.append( $('<label/>' ).append( str ) );
var searchFn = function() {
/* Update all other filter input elements for the new display */
var n = features.f;
var val = !this.value ? "" : this.value; // mental IE8 fix :-(
/* Now do the filter */
if ( val != previousSearch.sSearch ) {
_fnFilterComplete( settings, {
"sSearch": val,
"bRegex": previousSearch.bRegex,
"bSmart": previousSearch.bSmart ,
"bCaseInsensitive": previousSearch.bCaseInsensitive
} );
// Need to redraw, without resorting
settings._iDisplayStart = 0;
_fnDraw( settings );
}
};
var jqFilter = $('input', filter)
.val( previousSearch.sSearch )
.attr( 'placeholder', language.sSearchPlaceholder )
.bind(
'keyup.DT search.DT input.DT paste.DT cut.DT',
_fnDataSource( settings ) === 'ssp' ?
_fnThrottle( searchFn, 400 ):
searchFn
)
.bind( 'keypress.DT', function(e) {
/* Prevent form submission */
if ( e.keyCode == 13 ) {
return false;
}
} )
.attr('aria-controls', tableId);
// Update the input elements whenever the table is filtered
$(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
if ( settings === s ) {
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame...
try {
if ( jqFilter[0] !== document.activeElement ) {
jqFilter.val( previousSearch.sSearch );
}
}
catch ( e ) {}
}
} );
return filter[0];
}
As you know it datatables doesn't show in HTML, so its js.
How it looks, look at the search input
How I want it to look
you can use following code
oLanguage: {
"sSearch": ""
},
for Placeholder put the following code
$('.dataTables_filter input').attr("placeholder", "search...");

DataTable column filtering with dom-select column

I am using Jquery Datatable for my table and for filtering data I am following this example
DataTables > API > Multi-filter
This is working fine for regular columns. But I have some columns with drop downs as following.
For this column filtering is not working since it is considered the all entries of the drop down for filtering.
Can someone please suggest a way to put a filter for this king of column.
I am using DataTables version 1.10.7.
Thanks.
That was fun:
const table = $('#example').DataTable({
initComplete: function () {
this.api().columns().eq(0).each( function (index) {
const column = this.column(index);
const title = $(column.header()).text();
if(index === 2){
var select = $(`
<select class="form-control">
<option value="">Please choose</option>
</select>
`)
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
}else{
var input = $(`
<input class="form-control" type="text" placeholder="Search ${title}" />
`)
.appendTo( $(column.footer()).empty() )
.on( 'keyup change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search( val )
.draw();
});
}
});
}
});
Working JSFiddle here.
After correction by Mr. Polywhirl (Thank you!) I revisited the problem and adapted a previous answer:
(function() {
$.fn.dataTable.ext.type.search.selected = (data) => !$(data).is("select")
? ''
: $(data).val();
$.fn.dataTable.ext.order['dom-select'] = function(settings, col) {
return this.api().column(col, {
order: 'index'
}).nodes().map(td => $('select', td).val());
}
})();
var table = $('#example').DataTable({
"columnDefs": [{
"orderDataType": "dom-select",
"type": "selected",
"targets": 2
}]
});
$("#example select").on("change", function() {
var $this = $(this),
val = $this.val(),
cellPosition = table.cell($this.parents("td")).index(),
rowDate = table.row(cellPosition.row).data();
$this.find("option").each((k, v) => ($(v).val() === val)
? $(v).attr("selected", "selected")
: $(v).removeAttr("selected"));
rowDate[cellPosition.column] = $this.prop("outerHTML");
table.row(cellPosition.row).data(rowDate);
table.cell(cellPosition).invalidate().draw();
});
Another working example here.
Hope that helps!
Found an answer from this question.
To write our own filtering function, we have to extend the $.fn.dataTable.ext.search function of Datatable.The function has 5 parameters and you need the fourth parameter (the original data source for the row). This fourth parameter is a JavaScript array, where the original HTML code of the given columns of the given rows can be found.
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex,original,counter ) {
var filterValue = $('#filterField').val();
var valueToFilter6 = original[6]; // this is the column with select box
if( valueToFilter6.indexOf('value="' + filterValue) != -1){
return true;
}
return false;
}
);
A complete working example fiddle can be found here.

JQuery Autocomplete - show full menu on focus (from within WP shortcode)

I have a working autocomplete form. I would love it to show all the labels in the dropdown on a single click without having to type.
Stack exchange is full of great answers to this question and I have tried them all without success. I suspect the problem is that the whole thing is being loaded from within a Wordpress Shortcode. Would like to keep it that way if possible. Any help?
I have two inputs that use Autocomplete.
//create autocomplete compare box shortcode
function autocomparebox( $atts, $content = null ) {
return '
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(function() {
var blenders = [
{
value: "optimum-9400",
label: "Optimum 9400",
icon: "2015/02/optimum-9400-blender-60x60.jpg"
},
{
value: "optimum-9200",
label: "Optimum 9200",
icon: "2015/02/optimum-9200-60x60.jpg"
},
{
value: "optimum-8200",
label: "Optimum 8200",
icon: "2015/02/optimum-8200-60x60.jpg"
}
];
//autocomplete Input 1
$( "#blender" ).autocomplete({
minLength: 0,
source: blenders,
focus: function( event, ui ) {
$( "#blender" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#blender" ).val( ui.item.label );
$( "#blender-id" ).val( ui.item.value );
$( "#blender-icon" ).attr( "src", "http://bestblenderaustralia.com.au/wp-content/uploads/" + ui.item.icon );
return false;
}
})
//Autocomplete Input 2
$( "#blender2" ).autocomplete({
minLength: 0,
source: blenders,
focus: function( event, ui ) {
$( "#blender2" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#blender2" ).val( ui.item.label );
$( "#blender-id2" ).val( ui.item.value );
$( "#blender-icon2" ).attr( "src", "http://bestblenderaustralia.com.au/wp-content/uploads/" + ui.item.icon );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br></a>" )
.appendTo( ul );
};
});
// Focus on Input 1 on page load, focus on Input 2 after Input 1 option is selected
$(document).ready(function(){
$("#blender").focus();
$("#blender-icon").click(function(){
$("#blender").focus();
});
$("#blender-icon2").click(function(){
$("#blender2").focus();
});
$("#ui-id-1 li, #ui-id-1").click(function(){
/* if ($("#blender2").val().length > 0) {
$( "#compareform" ).submit();
} else { */
$("#blender2").focus();
// }
});
$("#ui-id-2 li, #ui-id-2").click(function(){
$("#blender").focus();
});
});
//Values of selected items are passed to URL
function compareurl(){
var url="http://bestblenderaustralia.com.au/" + document.getElementById("blender-id").value + "-vs-" + document.getElementById("blender-id2").value;
location.href=url;
return false;
}
//Make sure both inputs are filled before submission
function validateForm() {
var errorWarning = document.querySelector("#error-warning");
var successLoading = document.querySelector("#success-loading");
var x = document.forms["compareform"]["blender"].value;
var y = document.forms["compareform"]["blender2"].value;
if (x == null || x == ""|| y == null || y == "" || x == y) {
errorWarning.style.display = "block";
return false;
} else {
errorWarning.style.display = "none";
successLoading.style.display = "block";
return compareurl();
}
}
</script>
<form id="compareform" onSubmit="return validateForm();">
<div class="blender-compare-wrapper">
<div id="blender-label"></div>
<img id="blender-icon" src="http://bestblenderaustralia.com.au/wp-content/themes/x-child-icon/img/blender-thumb-placeholder.png" class="ui-state-default" alt="">
<input name="blendera" id="blender" placeholder="Type a blender..." onfocus="this.placeholder = """>
<input type="hidden" id="blender-id">
<span class="versus"> VS. </span>
<img id="blender-icon2" src="http://bestblenderaustralia.com.au/wp-content/themes/x-child-icon/img/blender-thumb-placeholder.png" class="ui-state-default" alt="">
<input name="blenderb" id="blender2" placeholder="Type a blender..." onfocus="this.placeholder = """>
<input type="hidden" id="blender-id2">
<input type="submit" id="comparesubmit" value="Compare">
<p id="error-warning">Please choose two different blenders.</p>
<p id="success-loading">Loading results...</p>
</form>
</div>
';}
//Add the shortcode
add_shortcode('autocomparebox', 'autocomparebox');
Thats not possible , because jquery autocomplete triggers only if any value changes inside the textblock , but showing all the labels is possible
Take a look at this Stack, but workaround in source will give you desired results
Thanks for your help, I did find a workaround and it's as easy as binding a focus event to fire off an empty Autocomplete search. Just replace #yourid with the ID of your input and you're good to go.
$("#yourid").bind("focus", function(){
if($(this).val()==""){
$(this).autocomplete("search");
}
});
Use the option minLengthset to 0
minLength: 0
Hope that helps

Jquery autocomplete in jsp

I am new in jsp and so in javascript and i am trying to create an autocomplete form with two text fields. Also i want the second one to take some value automatic according to the value of the first one. Well, i did a little research and i found in another topic a code snippet. The think is that when i put it in a single jsp page in netbeans it doesn't works.I think something is missing. Can you please help with that. Thanks.
Here is my code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<input id='fruit' name='fruit' type='text'>
<input id='details' name='details' type='text'>
<script>
var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];
$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }
})
.on( 'autocompleteresponse autocompleteselect', function( e, ui ){
var t = $(this),
details = $('#details'),
label = ( e.type === 'autocompleteresponse' ? ui.content[0].label : ui.item.label ),
value = ( e.type === 'autocompleteresponse' ? ui.content[0].value : ui.item.value );
t.val( label );
details.val( value );
return false;
});
</script>
</body>
</html>
FIDDLE
UPDATED

Categories

Resources