jquery keyup removeClass doesn't work - javascript

I have one question.
I am trying to make a addClass, removeClass button function for after the text length > 5 or something else.
So the addClass working fine in my code but removeClass doesn't work. What I am missing here or what I am doing wrong here anyone can help me in this regard ?
I have tried the following code also please click for DEMO:
// Keypress for active inactive button
$(".PGA51c").on('keyup', function() {
var ID = $(this).attr('data-id');
var cm = $('#PCm' + ID);
if (cm.text.length < 5) {
$('#sev' + ID).addClass('tCo');
console.log('OK');
} else {
$('#sev' + ID).removeClass('tCo');
console.log('Not OK');
}
});
});

Use text() instead of text in if condition.
$(".PGA51c").on('keyup', function() {
var ID = $(this).attr('data-id');
var cm = $('#PCm' + ID);
if (cm.text().length < 5) {
//-----^^^^^^--------------
$('#sev' + ID).addClass('tCo');
console.log('OK');
} else {
$('#sev' + ID).removeClass('tCo');
console.log('Not OK');
}
});

Related

A button should show/hide depending on whether or not there is value in input field

Right now the button shows when input is added to the input field, but if I remove the input the button doesn't hide.
My only idea for a solution is to divide the function into 2 seperate ones.
That is, one that adds the input to the input field on click, and then another functions that keeps track of input.val, and controls the hide/show effect of the button.
Would that be a better way of doing it?
$("#peopleInPopup").on('click', '.list-group-item', function() {
var peopleName = $(this).children("span").text();
var peopleID = $(this).children("span").attr("class");
var input = $("#friendsNames");
input.val(input.val() + peopleName + "");
if (input.val().length === 0) {
$("#checkButton").toggle(false);
console.log("button should NOT display");
} else {
console.log("button should display");
$("#checkButton").toggle(true);
}
$("#checkButton").click(function() {
var newParticipants = input.val();
socket.emit("addParticipantsToConversation", newParticipants);
$("#chatToInfo").append(", ", input.val());
$("#friendsNames").val("");
$(":mobile-pagecontainer").pagecontainer("change", $("#pagefour"), {
transition: "slidedown"
});
});
});
Just use show and hide from jQuery instead, perhaps? I assume you want this to happen as the input is changing, so I've thrown in keyup (could use onChange or alternatives).
Tweaking your code slightly...
$('input').on('keyup', function (event) {
let value = event.target.value;
if (value && value !== '' && value.length > 0) {
$('#myButton').show();
} else {
$('#myButton').hide();
}
})
With a markup...
<input id='input' />
<button id='myButton'>GO</button>
And some sort of base style...
#go {
display: none;
}
Do the trick?
I actually just found a solution to my problem. The code below makes it work:
$("#peopleInPopup").on('click', '.list-group-item', function(){
var peopleName = $(this).children("span").text();
var peopleID = $(this).children("span").attr("class");
var input = $("#friendsNames");
input.val(input.val() + peopleName + "");
$("#checkButton").toggle(true);
$("#friendsNames").on('input', function(event) {
if (this.value.length === 0) {
console.log("Works!");
$("#checkButton").toggle(false);
console.log("button should NOT display");
} else {
console.log("button should display");
$("#checkButton").toggle(true);
}
});
$("#checkButton").click(function(){
var newParticipants = input.val();
socket.emit("addParticipantsToConversation", newParticipants);
$("#chatToInfo").append(", ",input.val());
$("#friendsNames").val("");
$(":mobile-pagecontainer").pagecontainer("change", $("#pagefour"), { transition: "slidedown" });
});
});

Remove option with value = MRW if I checkbox if checked

I'm trying to remove a option with value equal to MRW if #natural_person_lives_in_ccs_0 is checked but if I unchecked the checkbox then the SELECT should be as it was by default meaning same options. This is what I did:
$(document).ready(function(){
var lives_in_css = $('#natural_person_lives_in_ccs_0').is(':checked');
if (lives_in_css) {
$(".shipping_from option[value='MRW']").remove();
} else {
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
});
But it's not working since Option1 is added by default and I don't know how to write this. I think to use .toggle() but don't know if it's the right one. I leave a Plunker here for testing. Any help on this?
Steps:
Check Yes option value=MRW should be removed
Remove the check from Yes option value=MRW as by default (same position)
Try to use the .change() function to accomplish your task here,
$('#natural_person_lives_in_ccs_0').click(function () {
var elem = $(".shipping_from option[value='MRW']");
if (this.checked) {
elem.remove();
} else if (elem.length == 0) {
$(".shipping_from").prepend('<option value="MRW">Option1</option>');
}
});
DEMO
The best way would be,
$('#natural_person_lives_in_ccs_0').click(function () {
$(".shipping_from option[value='MRW']").toggle(!this.checked);
$(".shipping_from option:eq(" + ((this.checked) ? 1 : 0) + ")").prop('selected', true);
});
DEMO
Write your script like bellow.
var showOptionsAcorrdingCheckbox = function(){
var lives_in_css = $('#natural_person_lives_in_ccs_0').is(':checked');
if (lives_in_css) {
$(".shipping_from option[value='MRW']").remove();
} else {
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
}
$(document).ready(function(){
$(':checkbox').change(showOptionsAcorrdingCheckbox);
});
DEMO
code:
$(document).ready(function(){
$(document).on('change', '#natural_person_lives_in_ccs_0', function(){
if($(this).is(':checked'))
{
$(".shipping_from option[value='MRW']").remove();
}
else
{
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
});
});

Remove class onclick anything else

This may seem like a really simple question, but I'm having a lot of trouble trying to get it to work.
I have a series of elements spread across different parts of a page.
<span class="click-element"><span>
---
<span class="click-element"><span>
--
<span class="click-element"><span>
I want to toggle a class ("active") on/off on each of them when they are clicked individually, this should also remove the class from all the others.
To do this, my function looks like this:
var targets = document.querySelectorAll('.click-element');
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function () {
var clicked = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function (a) {a.classList['remove']('active');});
}
else {
[].forEach.call(targets, function (a) {a.classList[a == clicked ? 'add' : 'remove']('active');});
}
});
}
But what I'm trying to do, is then remove the class when anything else is clicked in the document:
document.addEventListener('click', function () {
document.querySelector('.click-element.active').classList.remove("active");
});
However, the problem I'm having is the second event seems to just override the first. How can I fix this? Or is there a cleaner approach to do what I want?
No jQuery thanks
try to cancle the event bubbling like this:
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function(e) {
var clicked = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function(a) {
a.classList['remove']('active');
});
}
else {
[].forEach.call(targets, function(a) {
a.classList[a == clicked ? 'add' : 'remove']('active');
});
}
e.stopPropagation();
});
}
Keys:
targets[i].addEventListener('click', function(e) {...
e.stopPropagation();...
Try this :
var targets = document.querySelectorAll('.click-element');
var activeElement; // this should be some global variable
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function () {
if(activeElement){
activeElement.classList['remove']('active');
}
var clicked = this;
activeElement = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function (a) {a.classList['remove']('active');});
}
else {
[].forEach.call(targets, function (a) {a.classList[a == clicked ? 'add' : 'remove']('active');});
}
});
}
I think better solution will be to use event bubbling.
If you have a common container:
document.getElementById('#containerId').addEventListener('click', function(evt){
var element = evt.target;
if(element.classList.contains('click-element'){
//toggle active
element.classList[element.classList.contains('active') ? 'add' : 'remove']('active');
} else{
//remove the active from all elements
document.querySelectorAll('.click-element.active').forEach(
function (clickElement, index) {clickElement.classList[remove]('active')}
);
}
});
In your case you don't have child elements in the spans, but if you had you need to check if the clicked element is a descendant of the span.
try jQuery libraries it will make it easy
$( "span" ).removeClass( "yourClass" );
http://api.jquery.com/removeclass/

searching in LI using jquery

I am searching in list of 500 li's. using following code. but facing two problems. one when i press backspace very fastly after typing something, it is not captured. and also searching is case sensitive which i dont want. please suggest improvements in below code :
$('#find_question').bind("keyup", function() {
searchWord = $(this).val();
console.log("input length",searchWord);
if (searchWord.length >= 0) {
$('#leftSection li').each(function(i, data) {
text = $(this).text();
if (text.match(RegExp(searchWord, 'i')))
$(this).show();
else
$(this).hide();
});
}
});
Try this
The containsIgnoreCase comes from How do I make jQuery Contains case insensitive, including jQuery 1.8+?
Live Demo
$.expr[':'].containsIgnoreCase = function (n, i, m) {
return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
$function() {
$('#find_question').on("keyup", function() {
searchWord = $(this).val();
$('#leftSection li').hide();
if (searchWord.length >= 0) {
$('#leftSection li:containsIgnoreCase("'+searchWord+'")').show();
}
});
});

Why won't function output into this jQuery selector?

I'm hoping this is something silly I've done. I got a function unigref near the bottom, which (I believe) outputs a string. However, when I call the function to build a jQuery selector, I can't get it to work properly. I know that everything else works because when I use a static string the radio button is selected.
Here's my jsfiddle/9Edxx. Please help.
var checkCount = 0;
var maxChecks = 2;
$(document).ready(function() {
$("#test").click(function() {
alert($(':checked').length);
});
$(':checkbox[name=checkbox]').change(function() {
checkCount = $(':checkbox:checked').length;
if (checkCount >= maxChecks) {
$(':checkbox[name=checkbox]').not(':checked').attr('disabled', true);
$(":radio[value="+uniqref()+"]").prop('checked', true);
} else {
$(':checkbox[name=checkbox]:disabled').attr('disabled', false);
}
if (this.checked) {
$("td.label").append("<label>" + this.value + "</label>");
} else {
$("td.label").find(":contains('" + this.value + "')").remove();
}
});
$('#button').click(function() {
alert(uniqref());
});
function uniqref() {
return $("td.label").text().split('').sort().join('').replace(/\s/g, "");
}
});​
UPDATE: The typo has been correct, but the problem still exists.
http://jsfiddle.net/9Edxx/
Yeah it's really silly: It's just a typo.
$(":radio[value="+unigref()+"]").prop('checked', true);
should be
$(":radio[value="+uniqref()+"]").prop('checked', true);
with a lowercased Q instead of a G.
Also, you're calling uniqref() before actually updating the value of td.label.
Should be in this order:
if (this.checked) {
// ...
}
if (checkCount >= maxChecks) {
// ...
}
http://jsfiddle.net/7mvmT/7/
http://jsfiddle.net/7mvmT/6/
Basically this line:
$(":radio[value="+uniqref()+"]").prop('checked', true);
is called prematurely (before the checkbox is actually checked. A simple, ugly hack:
setTimeout(function(next) {
$(":radio[value="+uniqref()+"]").prop('checked', true);
}, 0);
solves it.
Also you had a typo as Niko mentioned.
No need for hack.
http://jsfiddle.net/dn7gM/
p.s.: only works for the 2 first radios, since not all ids are setted correctly ;-)

Categories

Resources