Reference HTML Elements by name (with square brackets in them) via javascript - 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

Related

Add class to dynamically changing element

I'm trying to use the attrchange plugin to listen to a change in one element and add a class to another element. Kind of novice to jquery and javascript and could use some help with this...
function navchange() {
document.getElementByClassName("sticky-element-cloned").addClass('shrinkwrap');
}
$(".sticky-element-original").attrchange({
trackValues: true,
callback: function (event) {
//event.attributeName - Attribute Name
//event.oldValue - Prev Value
//event.newValue - New Value
navchange();
}
});
Thanks for any insight.
Two things. Firstly, fix your DOM method to make it valid.
document.getElementsByClassName(".sticky-element-cloned")[0].classList.add("shrinkwrap");
Secondly - isn't the class sticky-element-cloned? Then why are you using sticky-element-original in your jQuery?
$(".sticky-element-cloned").attrChange({...});
Or (do one or the other, not both)
Change it in your JavaScript:
document.getElementsByClassName(".sticky-element-original")[0].classList.add("shrinkwrap");
On the navchange function you're mixing your pure Javascript with your jQuery. Try:
$(".sticky-element-cloned").addClass("shrinkwrap");

Check is style attribute does not exists using javascript selector method

I'm trying to only select ARTICLE items that do not have the style attribute set.
I could do this easily with jQuery but I'm using a library that is javascript only, called scrollreveal.
I can easy get items that have the style attribute using this ARTICLE[style].
But I want to reverse this and get items that do not have a style attribute, in the same way using a not equal to != operator on the selector.
I've tried this...
// scroll reveal article
window.sr = new ScrollReveal({ reset: false });
sr.reveal('ARTICLE[!=style]', {
duration: 1000
});
But it's not working as expected, does anyone know if its possible to achieve this using not equal too on a attribute selector?
Thanks in advance for any help on this.
Almost there. The :not pseudoclass should do the trick:
article:not([style])
Just use :not([style]):
const matches = document.querySelectorAll('div:not([style])')
console.log(matches)
<div id="foo" style="width:100px;"></div>
<div id="bar"></div>
<div id="baz"></div>
That is if I'm correct in assuming that sr.reveal uses document.querySelector internally.

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.

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

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);
}

Referencing the HTML select control currently being used

I have a javascript program to filter a list of things in a HTML select control by typing a regular expression into an input (text) box. I can do the following to correctly filter a specific select control:
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist(document.myform.myselect);
filter.set(this.value);
});
});
but I have used a custom attribute (something one can now do in HTML5) called data-filterable. The attribute will store the name of the select control that is to be filtered so that JS can use the name of the control to filter the list. This would be a good idea because I will have a general function to filter any select box rather than a specific one.
Any ideas how I do this? I need something like this in the HTML:
<input data-filterable='{"to":"#selectbox1"}' size="30" type="text" />
but I'm not sure exactly what I'm doing here and what to do with the JS.
Thanks guys :).
Try this:
<input data-filterable="#selectbox1" size="30" type="text" />
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist($($(this).data('filterable'))[0]);
filter.set(this.value);
});
});
To break down the expression $($(this).data('filterable'))[0]:
$(this) wraps this in a jQuery wrapper. In our context, since it's a jQuery keyup event handler, this references the <input> DOM node.
$(this).data('filterable') retrieves the contents of the data-filterable attribute as a string. In our case, it's #selectbox1.
After that this string gets passed in to jQuery as a selector: $($(this).data('filterable')).
Finally, we take the 0'th element of the returned array which should be the DOM element of the target selectbox. Of course, if there isn't a selectbox which fits the selector this will fail rather miserably. If you suspect that this is a real scenario, check the .length of the returned array first.

Categories

Resources