Remove specific text from a paragraph Jquery - javascript

In the code below there are check-boxes and every time a check box is checked it add that check-box value (works). But when it is unchecked it should remove that check-box value. But instead it is just adding the value twice. How do I add and remove that value that is unchecked?
Here is the code sample
//Looks for every checkbox
$('#index '+ selected +' #cbFieldSet .icheck').each( function(i, name){
console.log("#"+ $(name).attr("id"));
if($('input[name='+$(name).attr('name')+']').attr('checked', false)){
//checks what checkbox has been check. Gets that checkbox id
$('#index '+ selected +' #cbFieldSet #'+ $(name).attr("id")).click( function(){
// $("#cb-"+playerStart).click(function(){
//console.log(i);
console.log('yes');
//add to popup box paragragh
$('#popupDialog #info').append($(name).val());
});
}else if($('input[name='+$(name).attr('name')+']').attr('checked', true)){
//checks what checkbox has been check. Gets that checkbox id
$('#index '+ selected +' #cbFieldSet #'+ $(name).attr("id")).change( function(){
// $("#cb-"+playerStart).click(function(){
//console.log(i);
console.log('yes');
//add to popup box paragragh
$('#popupDialog #info').remove( ":contains("+ $(name).val() +")" );
});
}
});

This code is not easy to read, partly because you have copy-pasted the same comments in both the "checked" and "unchecked" cases. You've also left out some context-- the indentation is off, and I don't know what selected is.
Anyway-- in addition to what user3785863 has said above, the form of .attr() you're using sets attribute values, when you want to read the existing value.
In other words, $('input(...)').attr('checked', false) does not test whether the checkbox is checked; it sets its value to boolean false, and then returns the checkbox itself, which means your first if statement will always run, and the second one never will.
So, I think what you actually mean is if ($(...).attr("checked") == "false").
(I think you also have true and false the wrong way round, plus some other issues, but this might get you unstuck...)

Depending on which version of jquery is used, you might want .prop() rather than .attr().
Only versions pre-1.6 have attr("checked",true/false) i.e. as boolean.
.prop( "checked" ) should do the trick

Related

Select checkbox if not selected with Protractor

I try execute in protractor following scenario:
Find checkbox
Check if it is selected
If yes - go further
If not - select it and go further
For some reason isSelected() function is not working with my checkbox, but I've found some solution. Below code works correctly:
expect(checkbox.getAttribute('aria-checked')).toEqual('false')
It checks some checkbox attribute which is 'false' if not selected and 'true' if selected. (but as a string)
Now the main question. How to write an 'if / else' statement to make it works?
I tried something like that:
if (expect(checkbox.getAttribute('aria-checked')).toEqual('false')) {
checkbox.click();
}
But it always clicks on checkbox no mater if it was selected or not. I've tried also:
if (checkbox.getAttribute('aria-checked').toEqual('false')) {
checkbox.click();
}
But there is an error which says "It's not a function".
Could anybody help me with that?
You can use the below method to solve the problem.
Before clicking any any checkbox, check for the value of aria-checked attribute, if its true don't do anything. Otherwise click on it.
checkBoxElement.getAttribute("aria-checked").then(function(isChecked){
if(isChecked == "false") { //getAttribute will return the value as string.
checkBox.click();
}
})
You could try to make some helper function:
function setCheckBoxTo(locator, value){
var checkbox = element(locator);
checkbox.isChecked().then(function(selected){
if(selected !== value){
checkbox.click();
}
}
}
where [value is true/false]

javascript jquery dropdown listbox - How to set option text at specific index (not selected!)

My question is, using javascript / jquery, "How do you change the value of a dropdown option at a specific index that is NOT the selected index?"
I have a dropdown list of values. User can select an option. I have a method which enables the user to change the value at that selected option. The value gets changed and all is well.
Here is my issue: If the user decides to cancel, or changes to a different value in the list without saving the changes to the database, I want to undo the value change.
I have the index of the changed option.
I have the old value of the changed option.
I have the new value of the changed option.
If the user has selected a different option, I don't want to change the index of the newly selected option. I just want to reset the value of the option the user changed.
I've tried a .each method:
var changedTitle = $('#ddTitle').text();
$("#ddTitle option").each(function() {
if($(this).text() == changedTitle) {
$(this).text(savedTitle);
}
});
I like the idea of looping through each one but I never see execution loop through a second time and the browser never comes back.
I've tried a .filter method:
var changedTitle = $('#ddTitle').text();
$("#ddTitle option").filter(function(index) { return $(this).text() === changedTitle; }).attr('selected', 'selected');
$("#ddTitle option").filter(function() {
return $(this).text() === changedTitle;
}).prop('selected', true); // changes the selected option
I got the above filter code to work but it sets the selected option.
$("#ddTitle option").filter(function() {
return $(this).text() === changedTitle;
}).prop('text', savedTitle); // execution never returns
I tried using the text property on the option but jquery gets very busy and execution never returns.
I've tried finding by the text value, which is silly because I know the index:
$("#ddTitle option[value='" + theText + "']").attr('selected', 'selected');
If these get an option it is the first option (0) or the browser hangs.
Is there a way to change the text value at a specified index programmatically in javascript or using jquery? Nothing I've tried works.
To change the value of the 5th option, do:
$('#yourselect').children('option:eq(4)').html('your text');

Hiding Selected item with Jquery

I have this code
$("#tag_price").on('change', function(event) {
if ($(this).val() == -2)
$('<input type="text" class="ipt" id="customprice" name="customPrice" />').insertAfter(this),
$('<p id="customprice" class="semi_margin_top">Introduce el precio exacto</p>').insertAfter(this);
else if ($(this).val() !== -2)
$('#customprice').hide;
});
The first part is working, when the input has value -2, the second input is shown. But I want it to dissappear when another value is selected, because if not the second input will remain forever.
I want the second input ONLY to show when value -2 is selected, and dissappear when another value is selected. I thought I could achieve that with Jquery and hide, but I't wont work.
Thank you!
The corollary to hide() you're looking for is show(). There are a few other issues with your code that you'll need to take care of as well.
First, you're missing { } around your if statement, so your else if should be throwing an error as the $('<p...') line is outside of the if.
Secondly, there's no need for else if as there isn't a 3rd option. The value is either "-2" or it isn't.
Right now, you're appending a new element every time that someone selects the "-2" item, which is not the right way to do it. Check to see if those elements are already in the DOM, and only add them if they aren't there. If they are, then call show().
if ($(this).val() === -2) {
$('#customprice').show();
}

J.S not executing all commands

In the following code, each "Id" is connected to a checkbox, so when I check it a word is printed and if I uncheck it the word disappears.
function DrawRequest()
{
if(document.getElementById("name").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
if(document.getElementById("surname").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
if(document.getElementById("age").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
}
Or at least that is what should have happened when I tried the code. What really happened is that when I checked the checkbox with id "name" nothing printed. The also happened with the checkbox with id "surname." But the last checkbox with id "age" works fine!
One more question: if the three checkboxes are checked will Ihave three words printed ?
Thanks a lot :)
You always update the innerHTML for each box, whether it's checked or not. And each if or else will overwrite what the previous statements set, making the previous actions irrelevant.
You'll want to either:
set the innerHTML to blank at the beginning of the function, get rid of the elses, and only set the HTML to "checked" if a box is checked (not doing anything if it's unchecked), if you want one "checked" total if any box is checked;
append to the HTML rather than setting it, if you want a "checked" for each box; or
Have a separate element to reflect each box's checkedness.

Changing checkbox's parent element css if checked or unchecked

Basically I have a checkbox inside a td element and I want it to have one background color when the checkbox is checked and another background color when the checkbox is unchecked. So in other words I want it to highlight whether it's checked or not.
I tried to use the same solution as in here: Jquery toggle event is messing with checkbox value
But for some reason I can't get it working.
$(document).ready(function(){
$("input:checkbox").change(function() {
if($(this).attr("checked") === "true") {
// CHECKED, TO WHITE
$(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"});
return;
}
//NOT CHECKED, TO GREEN
$(this).parent().css({"background" : "#b4e3ac", "-moz-border-radius" : "5px"});
});
});
It does add the green background color but doesn't remove it. And if I leave a checkbox checked, refresh, the td is back to white and once clicking on the checkbox again, unchecking it, it changes the td's background to green.
I'm still new to this, have no idea what could be wrong here, been trying to figure it out for hours now. Such a simple thing but just can't get it working.
There is a better way to see if the checkbox has been checked:
$(this).is(':checked')
It is a bit more robust.
Change
if($(this).attr("checked") === "true")
to
if($(this).attr("checked") === true)
Snce you are comparing using strict equal the two data types must be the same.
typeof ( $(this).attr ( "checked" ) )
will let you know that it is of boolean type and you are comparing it to a string.
For more info see Comparison Operators
if ($(this).attr("checked") === "true")
attr does not read HTML attributes. It's deceptive that way. If it did read attributes, the string value for checked would be 'checked' and not 'true'. But it doesn't do that.
What it actually does is read JavaScript object properties, only using attribute names instead of property names in the few places they differ. The checked property gives you a boolean value so there's no need to compare it to anything, you can just say:
if ($(this).attr('checked'))
or, even simpler, the totally equivalent:
if (this.checked)
best one is
if($("this").is(':checked'))
{
$(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"})
}
Check out this article on the difference between =, == and === in javascript. Or this on equality operators in js.
Try changing this:
$(this).attr("checked") === "true"
to this:
!!$(this).attr("checked") === true
This will convert any non-boolean to a boolean and allow your type safe comparison to work even if the string "true" is returned (if the string false is returned it will evaluate to true though....)

Categories

Resources