How to use string argument of a function in a jQuery expression - javascript

I have some set of links and select boxes. My html code is below:
<div>
<div>
<a href='#' onclick='set_checked(false,"checkbox1")'>clear</a>
<a href='#' onclick='set_checked(true,"checkbox1")'>select</a>
</div>
<div>
<input type='checkbox' name='checkbox1'/>
</div>
</div>
<div>
<div>
<a href='#' onclick='set_checked(false,"checkbox2")'>clear</a>
<a href='#' onclick='set_checked(true,"checkbox2")'>select</a>
</div>
<div>
<input type='checkbox' name='checkbox2'/>
</div>
</div>
Now my requirement is when I click on select link I have to check the checkbox based on it's arguments, and reversal for clear. Here I'm passing two parameters. One is to pass Boolean value (i.e. if true check else uncheck) and another one is to pass name argument of a checkbox field. And I'm using the following function to check or uncheck a checkbox:
function set_checked(checked,inputFeildName){
$('input[name=inputFeildName]').attr('checked',checked);
}
but the above code is not working. And this is my fiddle http://jsfiddle.net/vu6fs/5/.
I have one more requirement, before selecting any checkbox all clear links have to be disabled, after selection of checkbox respective clear link have to be enable. I'm applying opacity and also 'disabled' property in JavaScript but it's not working,can anyone suggest me where my fault is.. Can anyone please help me?

jQuery 1.6+
function set_checked(checked,inputFeildName){
$('input[name="'+ inputFeildName +'"]').prop('checked',true);
}
jQuery 1.5 and below
function set_checked(checked,inputFeildName){
$('input[name="'+ inputFeildName +'"]').attr('checked','checked');
}
Here is an example for your extension of question (more you want, About disable/enable a tag on checkbox change)
CSS
.disButton {
background: transparent;
border: none;
}
.disButton a {
text-decoration: none;
color: #ddd;
}
jQuery
$('input:checkbox').on('change', function() {
enable_clear(this, this.checked);
}).change();
function enable_clear(el, checked) {
var target = $(el).parent('div').prev('div').find('a:contains(clear)');
if (checked) {
target.unwrap();
} else {
target.wrap($('<button/>', {
disabled: true,
'class': 'disButton',
width: target.width() + 'px'
}));
}
}
$('a').on('click', function(e) {
e.preventDefault();
var target = $(this).parent().next('div').find('input:checkbox');
if (!target.is(':checked') && $(this).text() == 'select') target.click();
if ($(this).text() == 'clear') target.click();
});
DEMO

I think this is what you are trying to do... btw you have misspelt field so be careful when using the variable/attr again.
function set_checked(checked,inputFeildName){
$('input[name="'+inputFeildName+'"]').attr('checked',checked);
}

you forget to append string that i did as below , this will resolve your issue
function set_checked(checked,inputFeildName)
{
$('input[name="'+ inputFeildName+'"]').attr('checked',checked);
}

There are some errors in your fiddle:
Your function set_checked is declared in the onLoad-Handler (as selected), and is only available in that locally and not in the global scope. Remove the wrapping function by selecting "no wrap (head)" or assign your function to window.set_checked.
Please note that the checked attribute only represents the default value of the checkbox, to change the actual state you need to use the checked property (with jQuery, you can use val()).
If you wanted to change the default value, you can't do it by setting the attribute to (the string) false. The attribute represents a checked checbox through its existence, you would need to use removeAttribute() for disabling. It's easier to use the defaultChecked property with a boolean value.
last but not least there's the obvious error detected by all others: To use a variable, you will need to use it instead of putting its name into a string (like in PHP).
You also might be more happy with ids than name attributes. I've updated your fiddle with a proper solution: http://jsfiddle.net/vu6fs/7/
To disable the clear/select link when it's not appropriate:
you can't disable a link (anchor) as you can a form element (see Disable link using javascript, jQuery disable a link, Disable link using css). OK, we don't really need to disable its functionality (nothing changes), so so I guess you only think of graying it out. This can be done with CSS, and you'll need to trigger the update both on user-change events and the setting through set_checked. Example code at http://jsfiddle.net/vu6fs/9/
It might be easier to use just one link that toggles the checked state. Its lettering may change between "clear" and "select", depending on the current state.
I now have written a plugin (i.e. a jQuery prototype function) to add those links dynamically to any checkbox elements. That means it also can use (scoped) click handlers instead of a global-scope-polluting set_checked function.

The function has a little error:
function set_checked(checked,inputFeildName){
$(**'input[name='+inputFeildName+']'**).attr('checked',checked);
}

Related

How can I toggle an element's attributes using pure JavaScript?

Most of the similar questions that arose as I wrote this one were like this (where the user wishes to toggle an element's class using pure JS) or this (where the user wishes wishes to toggle other attributes using jQuery)
My question is a mixture of the two. I am aware that the el.classList.toggle() method exists for toggling an element's class using pure JS, but I wish to toggle different attributes using pure JS, specifically the checked attribute of some radio buttons, since this (annoyingly) does not change when different options are selected.
Is it possible to toggle the checked attribute on my two radio buttons with pure JS (by toggling I mean remove the attribute from the element altogether if it is present, and add it if it is not)?
radios = document.getElementsByName("Floor");
for (i = 0; i < radios.length; i++) {
radios[i].addEventListener('change', function () {
this.(/*checked attribute*/).toggle()
}, false);
}
<input checked id="Floor" name="Floor" type="radio" value="0">Ground Floor
<input id="Floor" name="Floor" type="radio" value="1">First Floor
Edit: The possible duplicate question mentioned in the comments does not quite solve my problem. I don't need to change which radio button appears checked, I just want to toggle the checked attribute, to make it easier for me to reference the button that is checked later on in the code. Of course, if there is another, easier way of doing this, I'm all ears.
There actually is an Element.toggleAttribute method for boolean attributes. MDN Docs.
However, since it is not supported in IE, you might want to add the MDN Polyfill
there is no toggle method for attribute.
You can use:
elm[elm.hasAttribute('hidden')?'removeAttribute':'setAttribute']('hidden', '')
or
elm.hasAttribute('hidden') ? removeAttribute('hidden') : setAttribute('hidden')
EDIT: there is now toggle method for attribute.
elm.toggleAttribute('hidden')
https://developer.mozilla.org/docs/Web/API/Element/hasAttribute
This will work definitely well
const attrToggle = (el, attr) => el.getAttribute(attr) == 'false' ? el.setAttribute(attr, "true") : el.setAttribute(
attr, "false")
It's similar to native toggleAttribute.
I didn't test this, but this should do the trick.
radios = document.getElementsByName("Floor");
for (i = 0; i < radios.length; i++) {
radios[i].addEventListener('change', function () {
if ( this.checked ) {
this.setAttribute("checked", "false");
} else {
this.setAttribute("checked", "true");
}
}, false);
}
Element.toggleAttribute(name) used to toggle boolean attribute https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute
this.toggleAttribute("checked");
To anyone stumbling on this question, no one in comments or answers since 2017 seems to have pick up on the OP's incorrect assumptions on the true nature of the checked element attribute they are trying to 'toggle'. As this post has so far been viewed 19k times, here is the information you might actually be looking for:
<input type="radio" checked>
In this context the element's checked attribute is a flag developers can use to tell the browser to render a "checked" state on a radio or checkbox input on page load. After page load, the browser does not update or toggle this attribute when a user later selects or un-selects the input.
From MDN:
Checked: A Boolean attribute which, if present, indicates that this radio button is the default selected one in the group.
Therefore the approach of using Element.toggleAttribute('checked') suggested by some here, won't work as expected as the .toggleAttribute() method adds or removes the pre-render flag from the input, but doesn't update the element's 'checked' state as the OP is trying to do. Applying a boolean value to the attribute also has no effect on the state of the element: (this wont work) checked="false"
In JavaScript you can access the current state of an input through HTMLInputElement's IDL boolean property .checked, not to be confused with the Element attribute by the same name referenced by the OP. Here HTMLInputElement.checked is both a getter and setter, meaning you can access (and toggle the value of) .checked as follows:
<input type="radio" id="spam-machine" class="blackhat" name="spam-me" value="sure!">
<script>
const spamMe = document.querySelector('#spam-machine');
spamMe.checked = !spamMe.checked;
</script>
You can additionally selectively style checked inputs using the :checked CSS pseudo class:
input[type="radio"].blackhat:checked { visibility: hidden; }
Now go forth into the world .... rendering to no one evil for evil.

click then unclick jquery button not working

I'm trying to make a button which on one click it changes it's color, and on another click it returns to it's original form.
something like clicked and unclicked.
I added a JSfiddle for you to look at it.
https://jsfiddle.net/dw5y5xLx/3/
$('.genM').click(function() {
$('.genM').removeClass('selected');
$(this).addClass('selected');
});
thanks!
also, is there a way doing that by only using CSS HTML?
Thanks.
$('.genM').click(function() {
$(this).toggleClass('selected');
});
I have updated the js fiddle for you, please check (https://jsfiddle.net/dw5y5xLx/15/)!
jQuery hasClass function can be helpful
$('.genM').click(function() {
if($(this).hasClass('selected')){
$(this).removeClass('selected');
}else{
$(this).addClass('selected');
}
});
IDEA:
Is there a way doing that by only using CSS HTML?
Yes, there is a way how u could achieve that just by pure CSS and HTML. But, if you dont want to use js, you must have an HTML element that is able to keep the "pressed" or "unpressed" state all by itself, without js.
However, there is no such an HTML element, so you have to use something simmilar: Checkbox
<input type="checkbox"> have "checked" and "unchecked" state and it is practicaly the same as "pressed" or "unpressed".
SOLUTION:
The trick is to stylize the ckeckbox with CSS so it visually appears as a pressed or unpressed button. Here is an example how checkbox can be stylised - you need to modify the CSS in order to appear it like a button, not a toggle switch!
You will want to use CSS selectors like this (as shown in example):
input[type="checkbox"]:checked { ... },
input[type="checkbox"]:checked + .slider { ... },

Why does jQuery change event not work with select option?

The following code should enable the second select element (id=ANSWER.TTQ.MENSYS.8.) when the value in the first select element (id=ANSWER.TTQ.MENSYS.9.) changes, but it doesn't work and I've exhausted all the options I can think of, including those suggested already on this site. (NOTE: the element ids must be these values, hence I'm not using # to select them, as that doesn't work).
$(document).ready(function() {
$("input[id='ANSWER.TTQ.MENSYS.9.']").bind('change',function() {
alert ('this script runs');
$("input[id='ANSWER.TTQ.MENSYS.8.']").removeAttr('disabled');
});
});
If I substitute the enabled select (id=ANSWER.TTQ.MENSYS.9.) with a button and the change event with a click event; it works. So why not with change event on the select element?
Thank you for your help.
Firstly, you can select by id using the # character. Secondly you need to escape the . in the id attribute otherwise the selector engine will look for an element with the id ANSWER which also has TTQ, MENSYS and 9 as classes. Try this:
$("#ANSWER\\.TTQ\\.MENSYS\\.9\\.").bind('change', function () {
alert('this script runs');
$("#ANSWER\\.TTQ\\.MENSYS\\.8\\.").removeAttr('disabled');
});
Example fiddle
$(document).ready(function() {
$("#ANSWER.TTQ.MENSYS.9.").bind('change',function() {
alert ('this script runs');
$("#ANSWER.TTQ.MENSYS.8.").removeAttr('disabled');
});
});
select is not input( i.e. text input)

getting individual atrributes while selecting a class with JQuery

I'm new to javascript and JQuery, and I'm working in a small project with JSP.
I create a grid dynamically with JSP and I added some buttons wich class is "select" and in the alt attribute I set the current row index. That works perfectly, I'm trying to set the onclick dynamically. This is my code
$('.select').click(function (){
alert($('.select').attr('alt'));
}
I want to each button to show its own index, but that code shows just the first index in each button. I've searched how to do it, but nothing comes out.
Is there a chance to do what I want?
change this line as:
alert($(this).attr('alt'));
When jQuery calls your event handler it sets this to be the DOM element in question, so try this:
$('.select').click(function (){
alert($(this).attr('alt'));
});
If you need to access DOM element properties you can then get them directly, e.g.:
alert( this.id );
this.value = "test";
If you need to use jQuery methods on the element you need to pass it to the jQuery function first, e.g.:
$(this).hide();
$(this).css("color","red").slideDown();
$('.select').click(function (){
alert($(this).attr('alt'));
});
Change
alert($('.select').attr('alt'));
by
alert($(this).attr('alt'));
Now you select the attr alt of the button lauch the event.
Not sure if that's what you're looking for but...
$('.select').click(function() {
$('.select').each(function() {
$(this).attr('value', $(this).attr('alt'));
});
});
This'll have every button "show" the value stored within their alt attribute when you click one button.
By the way, if you're using 1 button per row, you'd probably better go with index().

Reference HTML Elements by name (with square brackets in them) via javascript

Hey everyone, I am trying to hide/show different html elements (div, etc...) based on whether a checkbox is checked or if a specific value is chosen from a dropdown box. I was wondering if someone can help me out. The html element is defined along the lines of this (below), and i'm not sure how to reference it by name with brackets in it. The page i'm using has jquery enabled, and i'd like to use it if possible. Thanks!
<input type="checkbox" name="addons[2]" />
Also - I cannot modify the checkbox's code.
jQuery to check if element is checked:
$("input[name='addons[2]']").attr("checked")
jQuery to loop over such elements that are checked:
$("input[name^='addons']:checked").each(function() {
// ...
});
Thanks for the help, here is the final code I used
$("input[name='customfield[4]']").click(
function()
{
if ($("input[name='customfield[4]']").is(":checked"))
{
$("#addons").hide();
}
else
{
$("#addons").show();
}
}
);
Here is an inline non-jQuery solution that bypasses the need to reference the square brackets entirely by using the javascript this keyword. Assuming you want to show/hide a <div> with id="mydiv":
<input type="checkbox" name="addons[2]" onclick="document.getElementById('mydiv').style.display = (this.checked ? 'block' : 'none');" />
avoid using [] in naming html elements

Categories

Resources