Ok, so I'm currently having an issue with the $.prop('checked') functionality. When unchecking some of my boxes, and using this function to read the checkboxes, all of them are still showing up as true when some of them should be showing up as unchecked. The part of the function that checks this is below, but some background: I'm using a table with input values in each td element and due to the way it's written, I'm having to gather all the info / validate / and check by using a td.each() function.
$("td", ele).each(function(idx){
var before = $('.e_content', this),
b_name = $('input:last[type!="hidden"], textarea:last, checkbox:last, select:last', this).attr('name'),
b_val = $('input[name="'+b_name+'"], select:last, textarea[name="'+b_name+'"]', this).val(),
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
after = function(){
before.hide();
$(ele).css("background", color);
$('td.edit', ele).show();
$('td.save', ele).hide();
$('span', this)
// WORKING ON TAKING THE VALUE OF THE .e_content FORM AND REPLACING THE SPAN WITH IT
.html(function(){
console.log(b_name+' : '+b_chx);
if(b_val != undefined && b_val != ''){
if(b_name == 'StageType'){
if(b_val == 1){ return 'Voice'; }
if(b_val == 2){ return 'Text'; }
if(b_val == 3){ return 'Email'; }
}
else if(b_name == 'qtrhour') {
return $('select', before).find(':selected').text();
}
else if(b_chx == true) { return '✓'; }
else if(b_chx == false) { return '✗'; }
else {
if(before.find('input:last').prop('type') != 'checkbox')
return b_val.replace(/\n\r?/g, '<br />');
}
}
})
.show();
};
$(this).html(after);
});
The problem is with this line:
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
It's coming up always as true even when the checkbox has been unchecked before the save button is hit. This function fires on the .save click event. Hopefully this is enough to determine what might be going wrong.
You can try the following,
$('input:checkbox[name="'+b_name+'"]', this).is(':checked');
To avoid issues regarding to checking or unchecking checkboxes, I normally use jQuery.attr()
$(...).attr('checked')
$(...).attr('checked','checked')
$(...).removeAttr('checked')
Also sometimes I check or uncheck them binding or triggering a .click() function.
Related
I want to hide or show an element based on if an input field has a value. Right now I have this, but the issue here is that it will add visible class every time a key is pressed and the value is not empty. Which is not correct and will lead to many problems down the line.
Is there a built in JavaScript event that I can use to check if the element is empty or not? What is the best way to do this with using the least amount of resources?
const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('input', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
}else{
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});
I think there is no such built-in thing.
You can do some improvement:
const query_input = document.querySelector(".query");
let btn = document.querySelector(".submit");
query_input.addEventListener('input', event => {
if (query_input.value.trim() == ""){
btn.classList.remove("visible");//remove
btn.classList.add("hidden"); //add
console.log ("empty");
}else{
console.log ("not empty");
btn.classList.remove("hidden"); //remove
btn.classList.add("visible"); //add
}
});
const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('blur', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
} else {
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});
For textboxes and numbers, If they are empty, We send the following error command very easily:
AJAX
parent_fieldset.find('input[type="text"], input[type="number"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
CSS
.input-error {
border-color: red;
}
But for select option, checkbox, radio tags, if they were empty, How should I do?
You may use something like this:
$(document).ready(function(){
$('#mySelectBox').each(function() {
if($(this).val() == -1)
$(this).addClass('input-error');
else
$(this).removeClass('input-error');
});
});
A fiddle example here. To clarify a bit, I assumed here that you'd have a "please select option" with the value -1 (so nothing was actually selected):
To verify if a combo box item has been selected, you can check the selectedIndex value.
With the checkbox, you can check its checked property.
Working example is at https://jsbin.com/hezemohali/edit?html,js,output
function verify() {
let selectCar = this.document.getElementById("car-brand");
if(selectCar.selectedIndex === 0)
selectCar.className = 'input-error';
else
selectCar.classList.remove('input-error');
let tc = this.document.getElementById("tc");
if (!tc.checked)
tc.parentNode.className = 'input-error';
else
tc.parentNode.classList.remove('input-error');
}
<script>
function no_email_confirm() {
if (document.getElementsByName("no_email")[0].checked == false) {
return true;
} else {
var box= confirm("Sure?");
if (box==true)
return true;
else
document.getElementsByName("no_email")[0].checked == false;
}
}
</script>
And here is my HTML for the checkbox:
<input type="checkbox" id="no_email" name="no_email" onchange="no_email_confirm()"></input>
For some reason, this gives me the confirm pop up the first time I check the box, but not for any click after that. Also, even if I click "Cancel" it still checks the check box. I've searched on here and for some reason, no matter what I try, I can't get it to work properly.
It should confirm if they really want to check the box, if they select "Yes" then it checks it, if not, then it doesn't check it. I can get it to work without the name no_email, but I can't change that..
Anyone have any ideas?
Looks like you've got several errors in there, most notably using == when you probably meant =. Instead, add an event listener and make sure the assignment works:
var box = document.querySelector('#no_email');
box.addEventListener('change', function no_email_confirm() {
if (this.checked == false) {
return true;
} else {
var confirmation= confirm("This means that the VENDOR will NOT RECEIVE ANY communication!!!!");
if (confirmation)
return true;
else
box.checked = false;
}
});
http://jsfiddle.net/A3VGg/1/
The following javascript (prototype 1.6) code hides all checkboxes on the page and inserts a div element with some css style and a click event to act as a fake-checkbox. It also looks out for a label next (or previous) the checkbox, to also trigger the same event.
When I click the div (fake_el) itself, everything works as expected, but when I try the same with the label, it only works one time. after that, the el isn't gonna change - as if it (the el) would be a value-parameter.
Any ideas here?
$$('input[type=checkbox]').each(function(el) {
if (el.visible()) {
var fake_el = new Element('div', { className:'checkbox checkbox_' + el.checked });
var label = (el.next() != null && el.next().tagName === 'LABEL' && el.next().readAttribute('for') === el.id) ? el.next() : undefined;
label = (el.previous() != null && el.previous().tagName === 'LABEL' && el.previous().readAttribute('for') === el.id) ? el.previous() : label;
var action = function(el) {
el.checked = (el.checked) ? false : true;
fake_el.className = 'checkbox checkbox_' + el.checked;
}
fake_el.observe('click', function() { action(el); });
if (label != null) { label.observe('click', function() { c.log(el); action(el); c.log(el); }); }
el.insert({ after:fake_el }).hide();
}
});
I changed a couple items and created a jsFiddle for this. First and foremost, c.log had to be changed to console.log for it to work for me :). After that, the only thing I changed was how the divs were added, since it wasn't working for me with insert. I set up some test data and away I went...
EDIT: Perhaps you don't have a non-label tag between two checkboxes and it is getting confused? Notice I have a br between label and the next checkbox, maybe you need to do something like that.
I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});