This section uses a checkbox to select your extras, once selected you move onto the next step and it will display your choice in a header called checkout[itemname]. When a check box is selected it changes a variable from false to true however my code doesn't seem to be doing that.
I will show an example section of the user selecting "Neck Tie" from the list of extras.
var hasNeckTie = false;
if (hasNeckTie = true) {
document.getElementById("checkoutnecktie").innerHTML = "Neck Tie";
}
<div class="three columns bear">
<h3>Matching Tartan Scarf (£2.50)</h3>
<label>
<input type="checkbox" autocomplete="off" name="scarf" id="scarf" value="2.5" />
<img src="Images/Scarft.png">
</label>
<p>Personalise your bear with a matching tartan scarf. It gets cold up here in Scotland, and this is the best way to keep your bear warm.</p>
</div>
<div id="checkoutnecktie"></div>
Any ideas why this code isn't running properly?
Your problem starts where you are using = instead of == in your if statement.
You are also trying to set the HTML value of an element which does not exist.
document.getElementById("checkoutnecktie").innerHTML = "Neck Tie";
You need to change "checkoutnecktie" to an element ID which exists.
You would need to hook an event to the checkbox.
You can do this with jQuery like so
$('#scarf').change(function(){
if($(this).is(":checked")) {
$('#checkoutnecktie').text('Neck tie');
}
}
Also like the other answer states, set the text to an element that exists.
Related
I'm working on a project with Java as the backend tech, JSPs and JS with jQuery on the frontend. I'm new to JS and jQuery or at least I'm no pro so I'm trying to do my best here.
So the thing is: I have this screen I'm working on, it shows two users or more and some information related to them. Each user (and its information) is on a different tab. Each user/tab has a checkbox that MUST be checked in order to go to the next screen. So if we have two users, both checkboxes MUST be checked. If we have five, all five of them. The screen is something like this (keeping in mind that the pink one is the selected user):
So the thing is, sometimes, my logic works well and I can move on to the next screen after checking all the checkboxes. But other times after refreshing the page, as I discovered using some console.logs, the checkbox on the first user is executing the code for all the checkboxes while the rest of the checkboxes are not doing anything. So I can't go on to the next screen unless I check the box in all the users and the first one last. The same happens if I uncheck a checkbox on the second user, it's not doing anything because its code is not executing.
I have a JS function on change that checks if all the checkboxes are checked in order to show the arrow to the next screen. Like this:
$("#demPricesCheckbox").change(function () {
var checkboxes = document.querySelectorAll("[id='demPricesCheckbox']");
var show = true;
for (var i = 0; i < checkboxes.length && show; i++) {
if (!checkboxes[i].checked) show = false;
}
if (show) {
ContractPrices.showForwardButton();
} else {
ContractPrices.hideForwardButton();
}
});
And my checkbox HTML reads as follows:
<label class="sub-checkbox" style="margin-left: 100px; margin-top: 5px">
<input
type="checkbox"
id="demPricesCheckbox"
name="demPricesCheckbox"
value="1"
/>
<branches:message code="NAME_OF_CHECKBOX" />
</label>
Any hints? I would appreciate any ideas or explanations on why this could be happening. If you need more info just ask me.
Thank you for your time! And pardon my bad English!
Your logic is close, but there are a few things to keep in mind.
HTML elements should have unique id attributes, meaning that you should never have more than 1 element with the same id on any page.
You should check the "state" of your user interface on every interaction – this is the foundation of reactive programming, and something that jQuery/React/Vue makes easy.
I've written and annotated some code that should help clarify.
// You have jQuery installed, so let's use that instead of vanilla
// This is a CSS selector for "all checkboxes in the DOM".
$("input[type='checkbox']").change(() => {
// Count how many checkboxes you have on the page
// You can use a different method
const totalNumberOfCheckboxes = $("input[type='checkbox']").length;
let countChecked = 0;
// Now, let's loop through them all and see if they are all checked
$("input[type='checkbox']").each((index, element) => {
// Increase the counter only if the checkbox is checked
if (element.checked) {
countChecked += 1;
}
});
// Now, let's check if they are all checked!
if (totalNumberOfCheckboxes === countChecked) {
// Enable your button
console.log("Enabling the next button");
$(".btn.next").removeAttr("disabled");
} else {
// Disable the button
console.log("Disabling the next button because all the checkboxes are not checked.");
$(".btn.next").attr("disabled", "disabled");
}
});
// Next button click listener
// This will only trigger when clicked, and the button is "enabled" – i.e.: not "disabled"
$(".btn.next").click(() => {
console.log('Go to the next page :)')
// This is just for the example – it disables all the checkboxes again
$("input[type='checkbox']").each((index, element) => {
element.checked = false;
});
});
// Setup
// This is not waiting for events, so it will run
// when the page is loaded
console.log("Disabling the next button because the page has just been loaded");
$(".btn.next").attr("disabled", "disabled");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="user1" type="checkbox" />
<label for="user1">User 1</label>
</div>
<div>
<input id="user2" type="checkbox" />
<label for="user2">User 2</label>
</div>
<div>
<input id="user3" type="checkbox" />
<label for="user3">User 3</label>
</div>
<button class="btn next">Next</button>
My HTML:
<div class="check" ng-repeat="point in dbs">
<input
name="db"
id="{{point.id}}"
ng-model="point.select"
ng-click="update($index, dbs)"
ng-checked="false"
type="checkbox"
ng-required="point.select" />
</div>
Whilst my update() function looks like:
$scope.update = function(position, dbs) {
angular.forEach(dbs, function(point, index) {
if (position != index)
point.select = false;
});
}
This works as with regards to tracking what the selected checkbox is, and sending into another controller that expects the value, all is working good.
However, when I go back from the resulting page, back to this search form again, somehow the checkbox I selected before, is preselected, and I don't want anything to appear, rather just have everything blank.
Would it be as easy as simply stating:
$scope.point.select = null;
as I can't seem to find a good solution for this, so that the checkbox is always blank / not pre selected when you arrive on this form.
Let me see if I get what you are doing. It looks like you are trying to make your list of checkboxes mutually exclusive. I might look at using a radio button list (a set of radio buttons with the same name attribute, HTML interprets this as a mutually exclusive list). If you create a variable which will hold the value of the selected option and pass that value around, you probably can achieve the same result with less code. Take a look here: https://jsbin.com/sunusihuse/edit?html,js,output
As for clearing the list of controls when you revisit the page, what I have described will do that too because the value of the variable which will hold the selected value is initialized to an empty string. Hope this helps.
i'm having a helluva time ascertaining the value of a checked radio button of a form and can't figure out why. this form has many radio buttons (options), maybe 50 or more. each option represents a color swatch. Note, the radio buttons themselves are not shown but is replaced instead with a color swatch image (maybe this is causing problems with the js).
there is a default option, and i need to run some code based on if the user has either selected this option or made no selection at all.
the markup for a swatches option looks like this.
<div class="threads-swatch-wrapper">
<input type="radio" name="id[9]" value="89" id="attrib-9-89" class="threads-radio-btn" />
<label class="attribsRadioButton two thread-opts" for="attrib-9-89">SL55<br />
<img src="images/attributes/SL55.jpg" alt="" width="260" height="320" />
</label></div>
the default option has no swatch image and looks like this
Please Select
the pseudo code would read something like:
if($('#color-swatches option:selected value = 182')) <!-- this the default --> {
'run some code';
} else {
'run some other code';
}
i've tried setting variables but they keep coming up undefined!
selected_val = $( "input:radio[name=id]:checked" ).val(); //undefined
You were nearly there - you just need to change your selector to check for names starting with id not equal to it. To do this, use the starts-with selector - name^=id:
selected_val = $( "input:radio[name^=id]:checked" ).val();
if(selected_val == '182') {
// run some code
} else {
// run some other code
}
See jsfiddle
I need to hide a button until a check box is clicked, however I am stepping into someone elses code who used tag libraries that did not define ID in the button tag. Here is what I have:
The button code:
<html:button name="Next" value="BTN.NEXT" styleClass="button" localeCd="<%= localeCd %>" onClick='Submit("Next")'/>
The checkbox code:
<input type="checkbox" name="fedCheck" onclick="checkFed(this, 'myNext')" value="y" />
The Javascript Code
function checkFed(ele, id) {
x = document.getElementById(id);
if (ele.checked == true) x.disabled = false;
else x.disabled = true;
}
I can get this to work in a seperate page but the page that it is on does not allow for the button to have an ID so it crashes every time. Any suggestions?
There would be better ways of doing this, listening for the click event, etc... but, to simply modify your code see this jsFiddle (note: this assumes this is the only element named "Next"):
function checkFed(ele, name) {
x = document.getElementsByName(name)[0];
x.disabled = !x.disabled
}
And change the onclick="checkFed(this, 'myNext')" to:
onclick="checkFed(this, 'Next')"
And add disabled="true" to the button so that it's initial state is disabled
...also note that this doesn't actually hide it like the title asks, it disables it, like the content of the question seems to ask.
Instead of finding the button using document.getElementById, use document.querySelector.
For example, if you have a single button on the page with "Next" as the value of its name attribute:
document.querySelector('button[name="Next"]')
as the title says i need to create a game but my problem is that I don't know how to read the radio buttons using javascript and based on the options, it generates a scenario with the game mode with the difficulty the player picks. I am using one text input for the nickname and 2 fieldsets like this one for the player to select the type of the game and difficulty.
<fieldset>
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="easy"> easy </input>
<input type="radio" name="dificuldade" value="medium"> medium </input>
<input type="radio" name="dificuldade" value="hard"> hard </input>
</fieldset>
I suggest you use jQuery, it makes life so much easier:
$('[name=dificuldade]:checked').val()
JSFiddle: http://jsfiddle.net/3bc9m/
Otherwise you would have to go through each of the radio buttons in the DOM, and check their checked property. When you find the one with checked === true, you can then read its value property. Like this:
var fieldset = document.getElementById('difficuldade'); // You'd need to set an ID to the fieldset element
var curr = fieldset.firstChild;
while (curr != null) {
if (curr.checked) {
break;
}
curr = curr.nextSibling;
}
curr.value; // This is your selected value
JSFiddle: http://jsfiddle.net/3bc9m/1/
As Nate mentioned, make sure the DOM is ready, otherwise this will not work. This means that all of your code should be run on the onload event of the body element. See this for more details: http://www.w3schools.com/jsref/event_body_onload.asp