Add Checkbox validation - javascript

Currently the date and year is being verified but I would like to add a checkbox to the list.
Form code:
var html = '';
html += '<div class="ac-overlay"></div>';
html += '<div class="ac-container">';
html += '<h2>' + settings.title + '</h2>';
html += '<p>' + copy.replace('[21]','<strong>'+settings.minAge+'</strong>'); + '</p>';
html += '<div class="errors"></div>';
html += '<div class="fields"><select class="month">';for(var i=0;i<months.length;i++){
html += '<option value="'+i+'">'+months[i]+'</option>'}
html += '</select>';
html += '<input class="day" maxlength="2" placeholder="01" />';
html += '<input class="year" maxlength="4" placeholder="2016"/>';
html +="<br><br>";
html +='<p><input class="smoker" type="checkbox"/>Please verify that you are a smoker.</p>';
html +="<br>";
html += '<button>Submit</button></div></div>';
Validation script:
validate : function(){
_this.errors = [];
if (/^([0-9]|[12]\d|3[0-1])$/.test(_this.day) === false) {
_this.errors.push('Day is invalid or empty');
};
if (/^(19|20)\d{2}$/.test(_this.year) === false) {
_this.errors.push('Year is invalid or empty');
};
_this.clearErrors();
_this.displayErrors();
return _this.errors.length < 1;
},
I played around a bit with the following code but something is missing:
if ("Not sure what to enter here to validate the checkbox.".test(_this.smoker) === false) {
_this.errors.push('You have not selected if you are a smoker');
};

Was a bit of a work around but ended up changing the Checkbox to enable and disable the verify button.
$(document).ready(function(){
$('#isAgeSelected').change(function(){
if(this.checked)
$('#autoUpdate').fadeIn('slow');
else
$('#autoUpdate').fadeOut('slow');
});
});
html +="<br><br>";
html += '<p><input type="checkbox" id="isAgeSelected"/> Please verify the date above is correct.';
html += '<div id="autoUpdate" class="autoUpdate" style="display:none"><button>Submit</button></div>';
html += '</div></div>';
See how it works here: http://jsfiddle.net/3WEVr/1135/

Related

Jquery assign value to select2 dropdown

I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?
Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??
1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
b. $row.find('select .row-item').val(item.itemID).trigger('change');
$(function() {
var data = data1
var html = '';
html += '<thead><tr>';
html += '<th>Item</th>';
html += '<th>Description</th>';
html += '<th>Qty</th>';
html += '<th>Total</th>';
html += '</tr></thead>';
html += '<tbody class="acc_table">';
data.forEach((item, index) => {
html += '<tr class="acc-row">';
html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
html += '</tr>';
//at here I assign the data to select2
$('select.row-item').eq(index).val(item.itemID);
});
html += '</tbody>';
$('.item tbody').empty();
$('.item').append(html);
$('.row-item:last').select2();
$('.item').DataTable({
"paging": false,
"ordering": false,
"info": false,
"searching": false,
});
})
const data1 = [{
"itemID": "10",
"itemName": "Item 1",
"itemQty": "1",
"totalAmount": "50.00"
},
{
"itemID": "20",
"itemName": "Item 2",
"itemQty": "5",
"totalAmount": "150.00"
}
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>
<table class="item">
On closer look, your line:
var $row = $(html);
$row is not used later on, so $row...whatever has no effect. You keep building the html and later do $('.item').append(html);.
So changing the select value within $row has no effect because $row is not appended, only the unchanged html variable.
As you're building HTML, you can add selected directly to the html:
html += '<option value="10"' + (item.itemID == 10 ? "selected" : "") + '>ITEM 1</option>'
html += '<option value="20"' + (item.itemID == 20 ? "selected" : "") + '>ITEM 2</option>'
Alternatively, if the html build can't be changed (or prefer not to, to keep it cleaner), add the itemID has a data-value and then use code later
html += '<select class="row-item" data-itemid="' + item.itemID + '">'
and then use jquery to set the .val(value) based on .data(itemid"):
$('.item').append(html);
$('select.row-item').each(function() {
$(this).val($(this).data("itemid"));
$(this).select2();
});
Note: you only need .trigger("change") after you've converted the select to a select2 - if it's not a select2 yet, then no need to call .trigger("change") (unless, of course, you have some other code that relies on this change and needs to run during initialisation, but would be better to explicitly call that rather than raise an event).

jQuery Mobile dynamic content -cannot select tag

I'm working with jQuery Mobile in a google web app and just having some issues selecting a tag. More specifically, I have content that is loaded from an external source so need to have a loading page initially. Once the external source is available I then update the page with the content using jQuery. Included in this content is an input tag. The issue is when I update the page, I cannot then cannot find the value of this input tag.
Here is my code below:
(intial html - Before content is loaded)
<div class="ui-body ui-body-a">
<div id="googleList" >
<fieldset data-role="controlgroup" data-mini="true" >
<input type="checkbox" name="checkbox-v-6a" id="checkbox-1-a">
<label for="checkbox-v-6a">Loading . . . </label>
</fieldset>
</div>
</div>
Here is my jQuery to update the code above when the new content comes in:
function showTaskList(tasks)
{
//Generate HTML
var htmlToInsert = "<fieldset data-role=\"controlgroup\" data-mini=\"true\" >";
for(var i = 0; i < tasks.length; i++)
{
htmlToInsert += "<input type=\"checkbox\" data-id=\"" + tasks[i][1] + "\" name=\"checkbox-" + i + "-a\" id=\"checkbox-" + i + "-a\" class=\"custom taskCheckBox\" ";
if(tasks[i][2] != undefined)
htmlToInsert += "checked=\"checked\"";
htmlToInsert += " />";
htmlToInsert += "<input id=\"currency-controlgroup1\" data-id=\"" + tasks[i][1] + "\" type=\"text\" value=\"" + tasks[i][0] + "\" data-wrapper-class=\"controlgroup-textinput ui-btn\" class=\"taskinputBox\">";
}
//Insert HTML into site
$("#googleList").html(htmlToInsert + "</fieldset>");
//Refresh List
$("#googleList").trigger("create");
}
Here is my code to get the input tag value
$(document).ready(function(){
function processTaskList()
{
console.log("Test");
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("data-id");
console.log("CheckBox:" + checkBoxId );
});
}
});
CheckBoxId keeps coming back undefined when I click on one of the checkboxes. I want to be able to read the data-id value. I'm not sure how to fix this? Any help is appreciated.
I tested the code below again, and it works - Thanks for your help
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("id");
console.log("CheckBox:" + checkBoxId );
});

Uncaught reference error with Prestashop Module

The error apears when i click the blue "add row" button". Any help trying to troubleshoot the problem?
Jquery is loaded before the tool and the script is run after the page is loaded
error occurs in line 9 of this code:
if($.isEmptyObject(num)) // check if any row already exist if not set 1
num = 1;
else // check if any row already exist if yes set max + 1
num = Math.max.apply(Math,num) + 1;
html += '<div id="megamenu-row-'+num+'" class="megamenu-row row">';
html += '<div class="clearfix">';
html += '<div class="add-column-button-container col-lg-6">';
html += ''+add_megamenu_column+'';
html += '</div>';
html += '<div class="remove-row-button col-lg-6 text-right">';
html += '<a class="btn btn-danger btn-remove-row" href="#" onclick="return false;">'+btn_remove_row_text+'</a>';
html += '</div">';
html += '</div>';
html += '<input type="hidden" name="row_content" />';
html += '</div>';
return html;
}
You might imported some products/categories with wrong \r or \n in their names and this brokes up back.js. Replace in /modules/tmmegamenu/views/templates/admin/additem.tpl on line 223
{addJsDef option_list=$option_select}
on
{addJsDef option_list=$option_select|replace:"\r":""|replace:"\n":""}
This should works.

Jquery validation plugin not working on dynamic generated checkboxes

Hey guys i am using Jquery validation plugin ,
I have to create a form which has dynamic generated fields like input boxes, select box and checkbox so it works perfectly on other elements of my form but not works for dynamic generated checkboxes
Check out the snapshot below
for this my jquery validate code is
var educationFormValidator = $("#educationForm").validate({
rules:function(){
var primaryEducationRules = new Object();
$('.is_primary').each(function() {
primaryEducationRules[this.name] = {
require_from_group: [1, ".is_primary"],
required:true
};
});
console.log(primaryEducationRules);
return primaryEducationRules;
},
messages:function(){
var messages = new Object();
$('.is_primary').each(function() {
messages[this.name] = { required: 'Please select relevant qualification' };
});
console.log(messages);
return messages;
},
submitHandler: function(form) {
form.submit();
},
invalidHandler: function() {
console.log( educationFormValidator.numberOfInvalids() + " field(s) are invalid" );
}
});
javascript function which generates dynamic check boxes
function addEducation (educationCount) {
var educationDiv = '<div class="inputRow_'+educationCount+'"><hr><br>';
educationDiv += addInstituteNameDiv (educationCount);
educationDiv += addBatchYears (educationCount);
educationDiv += addCourseType (educationCount);
educationDiv += addDegreeTypeDiv (educationCount);
educationDiv += addAddDegreeButton (educationCount);
educationDiv += '</div>';
$('.multiple-education').append(educationDiv);
//addYearsInOption(educationCount);
if(educationCount!=1){
$('#deleteDegreeBtn_'+(parseInt(educationCount)-1)).css("display","block");
$('#deleteDegreeBtn_'+educationCount).css("display","block");
}
$('#addDegreeBtn_'+ (parseInt(educationCount)-1)).css("display","none");
}
function addInstituteNameDiv (educationCount) {
var instituteNameDiv = '<div class="form-group" id="instituteName'+educationCount+'">';
instituteNameDiv += '<label style="padding-left:0;" class="col-md-2 col-sm-2 control-label" for="textinput">Institute</label>';
instituteNameDiv += '<div class="col-md-6 col-sm-6">';
instituteNameDiv += '<input name="From['+educationCount+'][otherInstitute]" class="form-control input-md" type="text" required id="instituteName_'+educationCount+'">';
instituteNameDiv += '</div>';
instituteNameDiv += '<!--<div class="col-md-1 col-sm-2"><span name="reset_'+educationCount+'" id="reset_institute_'+educationCount+'" class="suggestion-reset greentxt mt7 pull-left">Edit</span></div>-->';
instituteNameDiv += '<div class="checkbox col-md-3 col-sm-2 pdl0 col-xs-12 edu-message">';
instituteNameDiv += '<label style="padding-left:0;" for="checkboxes-0">';
instituteNameDiv += '<input class="is_primary" name="From['+educationCount+'][is_primary]" id="is_primary_'+educationCount+'" value="1" type="checkbox" onclick="setImportantEducation('+educationCount+')">';
instituteNameDiv += '<span name="primary_edu_'+educationCount+'" id="primary_edu_'+educationCount+'">This is my most relevant / important educational qualification</span>';
instituteNameDiv += '</label>';
instituteNameDiv += '</div>';
instituteNameDiv += '</div>';
return instituteNameDiv;
}
All fields are mandatory in form if it is generated but user have to select at least 1 relevant education out of many educations fields
for the help i have read this link too
you aren't calling addInstituteNameDiv() in your script. Also, addInstituteNameDiv() should appear before the validater call.
Try
jQuery.validator.addMethod("isprimary", function (value, element) {
return $('.is_primary:checked').length == 1;
}, "Please select 1");
$.validator.addClassRules("is_primary", {
isprimary: true
});
var educationFormValidator = $("#educationForm").validate({
submitHandler: function (form) {
form.submit();
},
invalidHandler: function () {
console.log(educationFormValidator.numberOfInvalids() + " field(s) are invalid");
},
errorPlacement: function (label, element) {
if (element.hasClass('is_primary')) {
element.parent().append(label)
} else {
label.insertAfter(element);
}
}
});
Demo: Fiddle
The accepted answer works, however, it contains some unnecessary code.
Eliminate .addClassRules():
You do not need the .addClassRules() method for simply applying a custom rule using a class. The .addClassRules() method is intended for creating a "compound" rule, which is not the case here.
If, for whatever reason, you wanted to create a custom rule, the custom rule can be applied directly as a class. There is no need for .addClassRules().
<input class="my_custom_rule" ...
DEMO: http://jsfiddle.net/m52ga6ex/12/

Edit a list of many elements with jQuery

I have like 100 (or more) elements in a list which is very similar to this:
$.ajax({
url:'mysite.it/ajax/list_filter.php',
data:data,
type:'POST'
}).done(function(data){
var reback = $.parseJSON(data);
var people = '';
if(reback.success){
if(reback.showcase){
$.each((reback.showcase),function(index,item){
var exists = $('ul#ul_people_list input[value="'+item.userid+'"]');
if(exists){
exists.parent('li').remove();
}
people += '<li>';
people += '<input type="hidden" class="username" name="username" value="' + item.userid + '"/>';
people += '<a class="show_dtl';
if(item.vip != 0){people += ' vip ';}
people += '" href="usr_dtl">';
people += '<div><img src="'mysite.it/pict_thumbs/' +item.pool_user_pict+ '" style="height: 80px; left: 1px;"></div>';
people += '<label>' +item.username+ '</label>';
if(item.vip != 0){people += '<span class="icon-star"></span>';}
people += '</a></li>';
});
if(refreshType == 2){//if refreshing
$('#people_list ul#ul_people_list').prepend(people);
} else {
$('#people_list ul#ul_people_list').html(people);
}
}
} else {
$('#people_list ul#ul_people_list').html('<li>' + reback.showcase + '</li>');}
});
When I refresh the list (about every 20 seconds) I have to add some element, update some element and delete some element.
I do all this with jQuery.
What is the best way, performance-wise, to do it?
At the moment I use the value attribute (in the second input element) to address the element I want to edit.
Is it better if I change my code to:
<li id="/* userid */">
Of course other suggestions are appreciated?

Categories

Resources