New to Javascript, teaching myself for fun. I have a basic function, and what I am attempting to do is make a checkbox (if checked) do more than one thing. In this example, I want to make a form become visible and also make the inputs required.
What I am noticing is that the first line works, I can make the form appear. However, the first input in that form does not become required.
Here is the Function.
When the checkbox is checked, the function does work. It makes the form "kForm2" become visible and hides it if not checked. But it seems it doesnt want to run the second line, where i require the first input of that form. There is also about 10 more inputs that I want to make required if that checkbox is checked. I know im writing this wrong, but I cant find the information online. Thanks
<input type="checkbox" id="k2Check" onclick="k2()">
<div id="kForm2" style="display:none">
<label for="kfirstname2">First Name:</label>
<input type="text" name="kfirstname2" id="kfirstname2"
minlength="3" maxlength="20">
</div>
<script>
function k2() {
var checkBox = document.getElementById("k2Check");
var kForm2 = document.getElementById("kForm2");
if (checkBox.checked == true){
kForm2.style.display = "block";
this.getField(kfirstname2).required=true;
}
else {
kForm2.style.display = "none";
this.getField(kfirstname2).required=false;
}
}
</script>
I was using the wrong code, after further research.
INCORRECT
this.getField(kfirstname2).required=true;
CORRECT
document.getElementById("kfirstname2").required = true;
This is working now thanks for your help guys.
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>
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.
This is my third night working on the same code... can`t get it right after days of google and tutorials and I am so tired of it... I am beeing desperate right now...
On short, I have a form and I use a button type="button" to generate a second button type="submit".
Before the second button appears, I need to check all required inputs if empty and after completion, show the second button.
I created a mixed code which now verify if inputs are empty, and highlights them one by one, not all inputs empty at the same time as I wanted.
I wanted to show highlighted all empty inputs not one by one and if one input is filled it should remove highlight class.
My work so far can be found here: here
Most important of all, I have a calculator which is calculating from inputs values. This is the reason I am using first button type="button".
How to get this to an end? I am so tired of this. Thank you.
LE: Partially fixed it by removing some return false; code from function. It has some errors although. For example, if you complete the last three inputs without completing and the ones on top, will submit anyway.
You could use the required attribute. It won't have any effects as you're not submitting the form, but then you could select all required fields with document.querySelectorAll(":required") or with jQuery $(":required") and loop through all of them validating each one.
You are returning false when a value is empty, so it's stopping the function, that's why they highlight one by one.
You can look this basic validation using JS and get idea what to do
<script type="text/javascript">
function validateMe(){
var name = document.getElementById('name').value;
var phone = document.getElementById('phone').value;
if(name==""){
//do something
alert("name can not be null");
return false;
//this will not submit your form
}
else if(phone==""){
//do something
alert("phone can not be null");
return false;
//this will not submit your form
}
else{
return true;
//This will submit your form.
}
}
</script>
<form action="somewhere.php" method="post" onsubmit="return validateMe();" >
<input type="text" name="name" id="name" />
<input type="text" name="phone" id="phone" />
<input type="submit" value="check and submit" />
</form>
NOTE: This is very basic validation using Javascript. What you want is to click one button and if valid then show submit button. But why you want do that if you want only validation. Why two buttons one to check values and show submit button and another button is submit itself. Why?
I created another short loop function BUT after inputs are filled, newButton button does not show. All Inputs are turning green from empty red. Please see the positioning of the return false;
function validateForm() {
var elements = document.getElementsByClassName("form-calc");
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
elements[i].style.borderColor = "red";
} else {
elements[i].style.borderColor = "green";
return false; // IF PUT THIS HERE, ONLY ONE INPUT AT A TIME IS HIGHLIGHTED BUT IN THE END THE newButton WILL POP UP.
}
}
return false; // iF I PUT THIS HERE IT STOPS HERE, NO NEWBUTTON NEXT.
var newButton = "<input type='submit' name='submit' value='Trimite-mi oferta pe mail' class='buton-calc'/>";
document.getElementById("a").innerHTML= "<span style='margin-left: 17%;'>Oferta personalizată a fost generată</span>"+newButton;
//SOME CODES HERE
});
What am I missing?
I can manage to get values from mysql using select box in php, but i can't make it with two-level chained select box.
Anyone have some example code or idea for that?
Thanks.
You're trying to handle clientside stuff, so you'll need to do this with javascript.
<input type="checkbox" name="chck_1" id="chck_1" onclick="javascript:setValue('chck_2');"/> Checkbox 1
<input type="checkbox" name="chck_2" id="chck_2"> Checkbox 2
In javascript you create a function:
function setValue(element)
{
var fieldElement = document.getElementById(element);
if(fieldElement.checked)
{
fieldElement.checked = false;
}
else
{
fieldElement.checked = true;
}
}
I haven't tested the code, but it should do ;)
Edit I've misread your post, but a similar thing can be done by setting it to selectboxes, only then you can fill it with the correct data when the first selctbox is selected to a specified index or something.
this is a small, but very annoying, glitch in my form.
I have a checkbox, that if clicked displays others checkboxes and input fields for the user to add more information. If this trigger checkbox is unclicked, the extra options dissapear.
However (the plot thickens), if another checkbox is checked in the form, the trigger checkbox can be checked and the extra options appear, but if unchecked the extra option won't dissapear!
(Sorry that was long winded, but i wanted to be clear!)
Here is my simple Jquery code:
$(function() {
var boxes = $('.obstruct-opt');
boxes.hide();
var ob = $('li.obstructionOptions').children().eq(0);
ob.change(function() {
if ($('$(this):checked').val()) {
boxes.show();
}
else {
boxes.hide();
}
});
});
I have tried different ways of checking if the trigger is checked or not, but any suggestions are welcome.
Edit
HTML as requested: (although simplified as my ASP.Net repeater control generated it)
<ul>
<li class="obstructionOptions">
<span>
<input id="Obstruction" type="checkbox" name="Obstruction" />
<label for="Obstruction">Obstruction</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProof" type="checkbox" name="WeatherProof"/>
<label for="WeatherProof">WeatherProof</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProofFlap" type="checkbox" name="WeatherProofFlap"/>
</span>
</li>
<li class="obstruct-opt">
<span>Obstruction Notes</span>
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
</li>
</ul>
Hope it helps!
Update:
substituting the if condition to
if ($(this).is(":checked")) {
doesn't trigger anything, no appearing or disappearing acts in sight.
Thanks for the suggestion tho, maybe with my html you can discern why?
Update
Ok after posting my HTML i realised ASP.Net has been stitching me up!
As you can see i select the 'ob' object as the first child, but the first child is a generated span! ASP has been wrapping my checkboxes in spans all this time and i never suspected! shrewd!
I have used this code in the end:
$('ul li.obstructionOptions span').children().eq(0).click(function() {
if ($(this).is(":checked")) {
boxes.show();
}
else {
boxes.hide();
}
});
Thank you to adamantium as this solved the prod perfectly!
Problem Solved!
Do not to trust ASP.Net with my markup!!!
What about replacing
if ($('$(this):checked').val())
with
if ($(this).is(':checked'))
is
Checks the current selection against
an expression and returns true, if at
least one element of the selection
fits the given expression.
Edit:
Replace
var ob = $('li.obstructionOptions').children().eq(0);
with
var ob = $('ul li.obstructionOptions span').children().eq(0);
and
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
with
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"></textarea>
and your code works fine.
Working Demo
It might have something to do with this line:
if ($('$(this):checked').val()) {
AFAIK, that won't do anything useful. You probably want this:
if ($(this).is(":checked")) {
ob.change(
A checkbox's onchange doesn't fire in IE until it's unfocused. For this reason it's usual to use onclick instead.
$('$(this):checked').val()
Doesn't work for two reasons. Firstly, you've included $(this) as part of the string. A dollar and brackets don't mean anything to selectors so jQuery won't match anything. You've already got the this object you want; you don't need to select anything more. Secondly, val() on a checkbox gets the value of that checkbox, not whether it is checked or not. This is the value attribute, or on if you haven't specified one.
Whilst you could test for checkedness using if ($(this).is(':checked')), it's more readable and much quicker to just use the standard DOM checked property. You don't have to shoehorn everything you do into jQuery.
ob.click(function() {
if (this.checked)
boxes.show();
else
boxes.hide();
});