I need to insert a checkbox into a form to change the font weight of text in a div.
My javascript is as follows:
function boldText(checkBox,target) {
if(checkBox.checked){
document.getElementById("lineOne").style.fontWeight = "bold";
}
else {
document.getElementById("lineOne").style.fontWeight = "normal";
}
}
And my html like so:
<input type="checkbox" onclick="boldText(this,textToBold)">
<div id="lineOne">Change text to bold</div>
What is wrong here. I cant seem to get it to work.
remove target it is undefined so it gives an error send id of div in single quate as follow
<script>
function boldText(checkBox,target){ if(checkBox.checked){
document.getElementById(target).style.fontWeight = "bold"; }
else
{ document.getElementById(target).style.fontWeight = "normal"; } }
</script>
<input type="checkbox" onclick="boldText(this,'lineOne')">
<div id="lineOne">Change text to bold</div>
refer jsfiddle
Just delete target in function argument and textToBold when you call it
http://jsfiddle.net/xArCc/1/
or
http://jsfiddle.net/xArCc/2/
There you go. The target should've been "lineOne" when you make the call.
Change this line to :
<input type="checkbox" onclick="boldText(this,'textToBold')">
Because "textToBold" is a string.
Related
I'm trying to add an input field on click of checkbox, and I want the checkbox to be checked (which is its default behaviour!), but the checkbox is not getting checked even after the input field appears. The following is my HTML code with JavaScript.
function check_test() {
if (document.contains(document.getElementById("test_input"))) {
document.getElementById("test_input").remove();
}
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()" />
</div>
I also tried this in JsFiddle which gives the same error and am not sure what I'm doing wrong.
https://jsfiddle.net/1yLb70og/1/
You're overwriting the content of the same div that the checkbox lives in, using innerHTML like that. Use a second div, or use create element and append child instead of replacing the entire contents.
This works.
<html>
<div id="test_div1">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()"/>
</div>
<div id="test_div"></div>
<script>
function check_test() {
if(document.contains(document.getElementById("test_number"))) {
document.getElementById("test_number").remove();
}
document.getElementById("test_div").innerHTML += "<input type='number' name='test_number' id='test_number'/>";
}
</script>
</html>
You're conditionally removing the #test_input if it exists in the DOM, but then you're not using an else when adding it. So no matter which state you're in, you'll always end the function with having added the input to the DOM.
As others have mentioned, when you += on the innerHTML, then you're actually creating a whole new string, thereby reinitializing your original checkbox to unchecked.
You may want to just append a new child to the wrapper. I've also used the onchange event instead so that it will do what you want no matter if the box is checked by a click or programmatically.
function check_test(checkbox) {
const checked = checkbox.checked; // is it checked?
const testInput = document.getElementById("test_input"); // test_input element
// if it's checked and doesn't have an input, add it
if (checked && !testInput) {
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'test_input';
newInput.id = 'test_input';
checkbox.parentNode.appendChild(newInput);
}
// otherwise, if it's not checked and there is an input in the DOM, remove it
else if (!checked && testInput) {
document.getElementById("test_input").remove();
}
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test(event.target)" />
</div>
By doing += you're overriding previous checkbox.
You could use:
document.getElementById("test_div").insertAdjacentHTML("afterend", "<input type='text' name='test_input' id='test_input'/>");
Instead of:
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
Not the greatest solution; however, it works and it's extremely simple. Then you just fix up the rest of the page with CSS styling.
Try adding an event in the function declaration:
function check_test(e)
Then calling e.checked; at the top or bottom of the function.
Let me know if that works.
Answering from my phone so I can't test myself.
When use innerHTML all events of the element is canceled.
You need to use DOM functions.
<html>
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test()" />
</div>
<script>
function check_test() {
var testdiv = document.getElementById("test_div");
if (!document.contains(document.getElementById("test_number"))) {
var newInput = document.createElement('input');
newInput.id = 'test_number';
testdiv.appendChild(newInput);
}else{
document.getElementById("test_number").remove();
}
}
</script>
</html>
related:
https://stackoverflow.com/a/595825/5667488
How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!
This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();
Have you checked if states[i][0] == input evaluates to true?
Write JavaScript code after html code end in your page or at the end of page.
I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;
The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.
I'm a beginner on this so please be patient with me. I have look up this problem and did not found a solution.
I have the following code:
on the head
<script>
function ledonoff(led)
{
if (document.getElementById('ck1').checked == true){
document.getElementById('led1').style.backgroundImage="url('Image/led_green.gif')";}
else {
document.getElementById('led1').style.backgroundImage="url('Image/led_red.gif');}
}
</script>
on the body
<div id="led1"></div>
<input name="" type="checkbox" id="ck1" onchange="ledonoff('led1')" value=""/>
I will like to have the function ledonoff take 2 parameters to be used in function : div id to be changed
and checkbox that is to be verified on the if of the function.
Can anyone help me with this.
Thank you
change the function to:
function ledonoff(led,checkBox){
var theDiv = document.getElementById(led),
check = document.getElementById(checkBox);
if (check.checked == true){
theDiv.style.backgroundImage="url('Image/led_green.gif')";
} else {
theDiv.style.backgroundImage="url('Image/led_red.gif')";
}
}
and the htmlonchange to:
"ledonoff('led1','ck1')"
in jsbin
Modify your code to:
<script>
function ledonoff(isChecked, elementId)
{
if (isCkecked){
document.getElementById(elementId).style.backgroundImage="url('Image/led_green.gif')";}
else {
document.getElementById(elementId).style.backgroundImage="url('Image/led_red.gif');}
}
</script>
And The body to:
<input name="" type="checkbox" id="ck1" onchange="ledonoff(this.checked, "led1")" value=""/>Led 1
You can simply pass it: onchange="ledonoff('led1', 'ck1')".
However your function is expecting one argument, so you need to amend that.
function ledonoff(led) -> function ledonoff(led, ck)
Just to note
This type of JavaScript is called Obtrusive Javascript. The recent shift in design principle is to have your Javascript and your HTML in completely separate files. Instead of assigning functions to events in an attribute fashion, you should use the DOM to add event listeners to DOM Elements. Here is a good tutorial to get you started on the idea.
do this:
<script>
function ledonoff(led,checkbox){
if(document.getElementById(checkbox).checked == true){
document.getElementById(led).style.backgroundImage="url('Image/led_green.gif')";
}else{
document.getElementById(led).style.backgroundImage="url('Image/led_red.gif')";
}
}
</script>
and your html:
<div id="led1"></div>
<input name="" type="checkbox" id="ck1" onchange="ledonoff('led1','ch1')" value=""/>Led1
i think, thats it. i assume your image paths are correct.
Use this.
</script>
function ledonoff(led,chk)
{
if (document.getElementById(chk).checked == true){
document.getElementById(led).style.backgroundImage="url('Image/led_green.gif')";}
else {
document.getElementById(led).style.backgroundImage="url('Image/led_red.gif');}
}
</script>
<div id="led1"></div>
<input name="" type="checkbox" id="ck1" onchange="ledonoff('led1','ck1')" value=""/>Led 1
I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2
I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.