JavaScript: change href value when box is checked - javascript

I have a button that links to a product page, like so...
<button>Buy This</button>
And I need to change the value of href when a box is checked. This is what I have so far
document.getElementById(#option1).checked = true;
document.getElementById(#link).value = '/product/option1.html';
But it's not working.
Thanks! :)

Of course it's not working...
getElementById, not GetElementById - case matters!
'option1', not #option1 - I don't know where you got the idea that #option1 was right.
You are setting the checked property to true, meaning the checkbox will be set to checked.
You have no event handler at all, so this code will only run once, when the page loads, and won't update when the user toggles the box.
A link's href is in its .href property, not its .value (it doesn't actually have a .value)
You have a <button> inside an <a> tag. Not technically valid, although most browsers will work the way you'd expect. This isn't a guarantee though, and you should either use a link, or a JS event handler on the button.
With all that in mind, I present to you...
<button id="link">Buy this</button>
<label><input type="checkbox" id="option1" /> Option text</label>
document.getElementById('link').onclick = function() {
if( document.getElementById('option1').checked) {
location.href = '/product/option1.html';
}
else {
location.href = '/product.html';
}
};

You added jquery as a tag, if you're using it, try this:
$(function(){
$("body").on("change", "#option1", function(){
$("#link").attr("href", "https://www.google.com");
});
})

Here is a nice demo I made in JSFiddle...
www.jsfiddle.net/Lvu5818f
document.getElementById("link").onclick = function() {
var link = document.getElementById("link");
var checkbox = document.getElementById("button");
if(checkbox.checked){
link.setAttribute("href", "#test2");
}
return true;
}
<button>Buy This</button>
<br>
<label><input type="checkbox" name="checkbox" value="true" id="button">Add an extra T-Shirt</label>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="test1">This is some text a long way away...</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="test2">This is some text even farther away...</div>

document.GetElementById('#link').href= '/product/option1.html';

Related

Detect click on input via the name attribute

I am trying to detect when one of these inputs are clicked and do a simple display none on a div. Everything I have tried will not detect a click. I do not have control over the html.
<div class="sibling csf--button csf--active">
<input type="radio" name="setting[open_btn_icon]" value="icon_a" data-depend-id="open_btn_icon">
</div>
<div class="sibling csf--button csf">
<input type="radio" name="setting[open_btn_icon]" value="icon_b" data-depend-id="open_btn_icon">
</div>
This is the last thing of many I have tried.
document.querySelector('[name="setting[open_btn_icon]"]').addEventListener("click", function() {
alert("Hello World!");
});
Right now all I am trying to do is detect the click. I can do the rest.
I have tried with jquery. I can do what I need when there is a class or id or a name whe nit not formatted as an array value.
I think your issue is the use of the querySelector method, which will only return a single element:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Consider using the querySelectorAll method, which will give you a NodeList that can be iterated over using a "for / of" loop.
In the end, your code would look something like:
let nodeList = document.querySelectorAll('[name="setting[open_btn_icon]"]');
for (let node of nodeList){
node.addEventListener('click', function(){
alert('Hello World!');
}
}
Alternatively
Consider applying a single listener to the parent DIV instead <div class="sibling csf--button csf--active">, then checking to see if the element being clicked is the one you need to react to. Depending on how many elements you actually need to react to, this could potentially help with performance.
It should fix your issue
let all = document.querySelectorAll('[name="setting[open_btn_icon]"]')
all.forEach(x=>x.addEventListener("click", function() {
alert("Hello World!");
}))
<div class="sibling csf--button csf--active">
<input type="radio" name="setting[open_btn_icon]" value="icon_a" data-depend-id="open_btn_icon">
</div>
<div class="sibling csf--button csf">
<input type="radio" name="setting[open_btn_icon]" value="icon_b" data-depend-id="open_btn_icon">
</div>
Three things could be improved to your code works:
addEventListener DOMContentLoaded to guarantee that when runs document.querySelectorAll the DOM is ready;
Change from querySelector to querySelectorAll tio get all inputs;
Rewrite rule that combines to get your inputs;
document.addEventListener("DOMContentLoaded", function () {
const allInputs = document.querySelectorAll(
'[name="setting[open_btn_icon]"]'
);
allInputs.forEach((input) =>
input.addEventListener("click", function () {
alert("Hello World!");
})
);
});

Get the first input checked

I'm trying to set the first input element in
<div class="containerplaatje klein">
<div class=slides>
<input...
"checked" and remove the "checked" status from all others.
The catch is:
Every time i click on a another container it has to set the first input element in that container to "Checked" and release every other.
See fiddle below:
https://jsfiddle.net/qa6not7w/
I thought this one was close, but I still got a failure:
$(document).ready(function info(){
$(".klein").click(function(){
if ($(this).hasClass("containerplaatje")) {
$(this).removeClass("containerplaatje");
$(".containerplaatje2").addClass("containerplaatje");
$(".containerplaatje2").removeClass("containerplaatje2");
$(this).addClass("containerplaatje2");
$(":input").attr ('checked', false);
/*$('input:radio[name=radio-btn][id=img-1]').attr('checked',true);*/
}
});
This sets the checkedness state of all radios to false, and then the first one to true:
$('input[type=radio]').prop('checked', false)[0].checked = true;
$('input[type=radio]').prop('checked', false)[0].checked = true;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" />
<input type="radio" checked />
<input type="radio" />
Note the use of prop in jQuery and properties in vanilla-js, instead of attr in jQuery and setAttribute in vanilla-js.
This did it for me:
$('input[type=radio]').prop('checked', false);
$(this).find('input[type=radio]').filter(':first').prop('checked', true);

Block btn until at least 1 checkbox of an offset is selected

A little frustrated here, somehow I can't make this work no matter what I try. I have a small form with 2 offsets, each containing a few checkboxes as the following:
<input type="checkbox" id="test1" /><label for="test1">
I need to make sure the user selects at least one of them in each offset in order to be able to click this button, otherwise it should be unclickable :)
<div class="offset6">
<a class="btn btn-warning" href="#openModal">CONTINUAR<span class="btn_caret"></a>
</span></button>
</div>
This should work for you:
//listen for changes to any checkbox so we can re-evaluate the button state
$("input[type='checkbox']").change(function(){
validateInput();
});
//checks to see if the button should be enabled or not
function validateInput(){
//get the count of checked items in each of the offsets
var offset3Count = $(".offset3").find("input[type='checkbox']:checked").length;
var offset8Count = $(".offset8").find("input[type='checkbox']:checked").length;
//set the disabled state of the button based on the offset counts
$(".btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
}
//call the function on page load to ensure the button is initially disabled
validateInput();
Here is a working example (I had to change your HTML a bit as it was invalid)
If you need a specific .btn, as in the one in offset6, then use this line instead:
$(".offset6 .btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
Here is the example
A quick recommendation: If you have unique elements then consider using an id attribute for them. For example:
<button id="btn6" ...>
With the following JQuery selector:
$("#btn6")...
Try
var chk = $(".offset3,.offset8").find('input[type="checkbox"]'); //cache your selector
chk.change(function () {
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', chk.filter(':checked').length);
});
chk.filter(':checked').length get length of checked checboxes
$('.btn').prop('disabled', $('input[type="checkbox"]:checked').length);
Updated After OP's Comment
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', $('input[type="checkbox"]:checked').length);
or add and id to than use # id-selector

Javascript function changeImage: Issues using variables for getElementById or getElementsByName

I'm having some trouble getting my code to do what I want. I have multiple sections that I have set to toggle show/hide, and it functions correctly. However, I'm now trying to switch the images to where instead of always being static with "More," I'd like it to switch to "Less" when it's expanded.
It does work... but only for the first one. If I press the buttons on any of the others, it only changes just the first one. You can see the page here:
http://jfaq.us
I've tried several different solutions with variables, but I can't seem to get it to work.
Help? Thanks in advance!
function changeImage() {
if (document.getElementById("moreorless").src == "http://jfaq.us/more.png")
{
document.getElementById("moreorless").src = "http://jfaq.us/less.png";
}
else
{
document.getElementById("moreorless").src = "http://jfaq.us/more.png";
}
}
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none")
{
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
<div>
Guestbook
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para3')" >
</div>
<div id="para3" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
About
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para2')" >
</div>
<div id="para2" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
</div>
The id attribute must be unique. That's why it's not working. Also, it's not a good idea to use inline event handlers like you are doing, you should register event handlers using addEventListener instead.
Without changing all your code, one thing you can do is pass a reference to the currently clicked element to the changeImage function.
function changeImage(el) {
var moreUrl = 'http://jfaq.us/more.png';
el.src = el.src === moreUrl? 'http://jfaq.us/less.png' : moreUrl;
}
Then change the inline handler for onclick="changeImage(this);"
You are using same Id for all inputs. This is causing the problem.
Give every element a unique Id.
If you want to perform grp operation use jquery class.
That's because you use the same id for the both images, and getElementById apparently takes the first one.
Here is the updated code:
html:
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage.call(this);return toggleMe('para3')" >
script:
// inside the event handler 'this' refers to the element clicked
function changeImage() {
if (this.src == "http://jfaq.us/more.png") {
this.src = "http://jfaq.us/less.png";
} else {
this.src = "http://jfaq.us/more.png";
}
}
check this
http://jsfiddle.net/Asb5A/3/
function changeImage(ele) {
if (ele.src == "http://jfaq.us/more.png")
{
ele.src = "http://jfaq.us/less.png";
}
else
{
ele.src = "http://jfaq.us/more.png";
}
}
<input type="image" src="http://jfaq.us/more.png" onclick="changeImage(this);return toggleMe('para3')" >

Javascript/jQuery issue

I'm trying to make radio buttons that when you have them active, it displays a dropdown. I can already make it display, but when I click on another radio button, it shows one, but doesn't hide the other...
Code:
<input type='radio' name='op' onchange='$("#ban_length").fadeToggle();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeToggle();'/>
JavaScript section:
$(document).ready(function() {
$('#op1').change(function(){
$("#ban_length").fadeIn();
$("#rank_list").fadeOut();
});
$('#op2').change(function(){
$("#ban_length").fadeOut();
$("#rank_list").fadeIn();
});
});
HTML:
<input type='radio' name='op' id='op1'/>
<input type='radio' name='op' id='op2'/>
<div id="ban_length">demo</div>
<div id="rank_list">demo</div>
Demo:
http://jsfiddle.net/b2UPt/1/
<input type='radio' name='op' onchange='$("#ban_length").fadeIn();$("#rank_list").fadeOut();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeIn();$("#ban_length").fadeOut();'/>
Though I would suggest removing the javascript from the elements themselves, giving them ids and adding the javascript to a separate script with $(theID).change(function(){....
Alternatively, you can use hide instead of fadeOut if you would like them to hide immediately.
And one last suggestion. If there are many of these and not just 2, I would add a shared class to each of the elements you are fading in. Then instead of hide on each element, just call $(".className").hide() to hide any that might be visible.
The change event only fires on the element that was clicked (i.e. the radio button that is now enabled). It isn't fired when a radio button is automatically disabled.
So you need to check all the radio buttons every time one of them triggers the change event. You need to be able to tell them apart, though, so start by giving them ids:
<input type="radio" name="op" id="radio_ban_length" />
<input type="radio" name="op" id="radio_rank_list" />
After that, you can use them to toggle the correct dropdowns:
$('input:radio').change(function() {
var id = $(this).attr("id");
if (id === "radio_ban_length") {
$("ban_length").fadeIn();
$("rank_list").fadeOut();
} else {
$("rank_list").fadeIn();
$("ban_length").fadeOut();
}
});
Alternatively, if you like a challenge or if you might have more than two radio's, you could use filter() and :checked to do something like this:
function getDropdownId(radioId) {
return '#' + radioId.replace(/^radio_/, '');
}
var radios = $('input:radio');
radios.change(function() {
// Checked radio's:
radios.filter(':checked').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeIn();
});
// Unchecked radio's:
radios.filter(':not(:checked)').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeOut();
});
});
Note that this method does rely on the id's of the radio buttons matching those of the dropdowns (e.g. radio_ban_length for ban_length).
Update: here is a live example: http://jsfiddle.net/55ANB/1/
add id="ban" and id="rank" to your radios
in your jquery section, add the click handler to the radio buttons
$(':radio').click(function() {
if ($(this).attr("id") == "ban") $("ban_length").fadeToggle();
if ($(this).attr("id") == "rank") $("rank_length").fadeToggle();
});

Categories

Resources