this is a sample code of what I am doing. unfortunately the alert(nextElem.value) returns "undefined" when I click the second checkbox to get the href of the link after it. do you have any idea how to fix it?
<HTML>
<HEAD>
<TITLE>Checkbox Inspector</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
for (i = 0; i <(document.f1.checkThis.length) ; i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem.href);
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="f1">
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate()">Check here<BR>
click here
</FORM>
</BODY>
</HTML>
Get the link's href with jQuery
http://jsfiddle.net/mplungjan/H9Raz/ :
$('form input:checkbox').click(function () {
alert($(this).nextAll('a').attr("href"));
});
Because of the BRs we need the nextAll, surprisingly since I was using the next selector with an "a"
See here why it did not work: Cleanest way to get the next sibling in jQuery
Get the link's href with forms access and usage of ID - no jQuery
http://jsfiddle.net/mplungjan/fKE3v/
window.onload=function() {
var chks = document.getElementsByName('checkThis');
for (var i=0;i<chks.length;i++) {
chks[i].onclick=function() {
var id = this.id;
var linkId="link_"+id.split("_")[1]
alert(document.getElementById(linkId).href)
}
}
}
<form>
<div>
<input type="checkbox" name="checkThis" id="chk_1" value="http://www.google.com" />Check here<br/>
click here<br>
<input type="checkbox" name="checkThis" id="chk_2" value="http://www.bing.com" />Check here<br/>
click here
</div>
</form>
Forms access to get the next checkbox
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate(this.form)">Check here<BR>
<INPUT TYPE="checkbox" NAME="checkThis" onClick="validate(this.form)">Check here2<BR>
function validate(theForm) {
var chk = theForm.checkThis
for (i = 0; i <chk.length) ; i++) {
if (chk[i].checked) {
var nextElem = chk[i+1];
if (nextElem) alert(nextElem.value);
}
}
}
Your problem is that nextElem is the text node immediately after your checkbox, not the next checkbox; text nodes don't have value attributes. For example, try this:
function validate() {
for (i = 0; i < (document.f1.checkThis.length); i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem);
alert(nextElem.value);
}
}
}
Or, for your convenience:
http://jsfiddle.net/ambiguous/sUzBL/1/
Related
I have created multiple checkboxes using a script in an HTML file.
I want to updates the checkboxes using name based on a condition like the below.
Checkboxes[I].checked = true;
But it's throwing an error.
Can you please suggest a way to solve this issue out.
for this purpose I will try to answer you, I have two options, by class or tag name, may if you want to use Jquery its also nice. I prepare an example for you, I hope that this one helps you, greetings
function toggleA() {
var elm = document.getElementsByClassName('chx');
for(var i = 0; i < elm.length; i++) {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
function toggleB() {
var elm = $(".chx").prop("checked")
$(".chx").prop( "checked", !elm );
}
function toggleC() {
var elm = document.getElementsByTagName('input');
for(var i = 0; i < elm.length; i++) {
if(elm[i].type.toLowerCase() == 'checkbox') {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" onclick="toggleA()">Toggle A</button>
<button id="btn" onclick="toggleB()">Toggle B</button>
<button id="btn" onclick="toggleC()">Toggle C</button>
<br><br>
<label>
<input id="check-a" class = "chx" onchange="alert('Changed A!')" type="checkbox"> A
</label>
<br><br>
<label>
<input id="check-b" class = "chx" onchange="alert('Changed B!')" type="checkbox"> B
</label>
<br><br>
<label>
<input id="check-jq" class = "chx" onchange="alert('Changed JQ!')" type="checkbox"> JQ
</label>
<br><br>
<label>
<input id="check-c" class = "chx" onchange="alert('Changed C!')" type="checkbox"> C
</label>
I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>
I want to create javascript code that will save all checkbox that user clicked and when user click on button finish, code will show him what he chose.(Text in label )
Honestly I do not have an idea and need help.
Is that possible to achieve on this way :
<html>
<script>
function test()
{
if(document.getElementById("chk").checked)
{
// save in some variable nad print on the end.. That is my problem.. and i have no idea.
}
}
</script>
<body>
<input type="checkbox" id="chk">
<label>someTXT</label>
<input type="button" onclick="test();"></input>
</input>
</body>
</html>
Exmaple to return all checked checkboxes (if you have more than one):
test = function() {
var checkboxesIDs = '';
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if(inputs[i].checked == true) {
checkboxesIDs+= inputs[i].id +", ";
}
}
}
alert(checkboxesIDs);
}
and HTML:
<input type='checkbox' id='c1' />
<input type='checkbox' id='c2' />
<input type='checkbox' id='c3' />
<input type='checkbox' id='c4' />
<input type='button' onclick="test();" value="Test" />
DEMO: http://jsfiddle.net/47EdX/
Here's a short example that figure out how to get this:
JS Function to check through checkboxes:
function checkAll(bx) {
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
HTML
<input type="checkbox" onclick="checkAll(this)">
You have to complement with some Array or object that will stores some value to push into the server.
Hope this helps.
$("input[type='button']").click(function(){
$cb = $("input[type='checkbox']").prop("checked");
$cb.each(function(){
alert($(this).attr("id"));
});
});
That's the way to access ALL checkboxes on your page and popup each id. You can also show any other attribute of your checkboxes like value or name.
My input texts work fine when i click the 'Edit HTML Below then Click Display' button, but my tinymce textareas won't work when I edit them. They'll send it's old value to the iframe, but not the new value. How can I send the new values when I edit the tinymce textareas? Here's the jsfiddle: http://jsfiddle.net/Ms3NG/1/ and code below:
<script type="text/javascript">
function init(buttonid, name, iframeid) {
document.getElementById(buttonid).addEventListener('click',function() {
// this.style.backgroundColor = '#cc0000';
gJSL_displayInput(name, iframeid)
},false);
gJSL_displayInput(name, iframeid);
}
window.onload = function() {
init('thisButton','test','iframetest');
init('thisButtona','testa','iframetesta');
init('thisButtonb','testb','iframetestb');
}
function gJSL_displayInput(nameInput, idOutput) {
var loc = "::JSLearning::gJSL_displayInput()";
try {
var ifrm = document.getElementById(idOutput);
var cnt = (ifrm.contentWindow || ifrm.contentDocument);
var doc;
doc = cnt.document;
doc.open();
var inputs = document.getElementsByName(nameInput);
for(var i = 0; i < inputs.length; i++) {
doc.write(inputs[i].value + "<br />");
}
doc.close();
} catch (e) {
exceptionAlert(loc, e);
}
}
</script>
<script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script>
tinymce.init({selector:'textarea'});
</script>
<div class="scrollbar">
<input id="test1" name="test" value="ajkla;ldkfj">
<input id="test2" name="test" value="bla2">
<input id="test3" name="test" value="bla3">
<input id="test4" name="test" value="bla4">
<input id="test5" name="test" value="bla5">
<br><br>
<textarea class="ckeditor" id="test6" name="test"></textarea>
<br><br>
<input id="test7" name="test" value="bla7">
<br><br>
<textarea id="test8" name="test">HELLO WORLD</textarea>
<br><br>
<textarea id="test9" name="test">HI EVERYBODY</textarea>
<br><br>
<input id="thisButton" type="button" name="Display" value="Edit HTML Below then Click to Display"/>
</div>
<div class="scrollbar"><iframe id="iframetest" src="" style="background: White;"></iframe></div>
You can use this code:
content8 = tinyMCE.get('test8').getContent();
doc.write(content8);
content9 = tinyMCE.get('test9').getContent();
doc.write(content9);
to get the values from the tinyMCE updated values.
Check this JSFiddle that I've build for you.
The last time I used tinyMCE, it doesn't have autoupdate textarea feature..
So, before submit the form, use .getContent() to update your textarea..
here is the link http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
So, your code will looks like
function gJSL_displayInput(nameInput, idOutput) {
var loc = "::JSLearning::gJSL_displayInput()";
try {
var ifrm = document.getElementById(idOutput);
var cnt = (ifrm.contentWindow || ifrm.contentDocument);
var doc;
doc = cnt.document;
doc.open();
var inputs = document.getElementsByName(nameInput);
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].tagName == 'TEXTAREA')
doc.write(tinyMCE.get(inputs[i].id).getContent() + "<br />");
else
doc.write(inputs[i].value + "<br />");
}
doc.close();
} catch (e) {
exceptionAlert(loc, e);
}
}
Look at this HTML example:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
And the resulting output from it:
I hope to send the checked checkbox to the servlet, but i also want to get the order user selected these checkbox.
For example,user A do stuff like : select Cheese,select Butter, select Milk->then Cheese,Butter,Milk will be sent to servlet with this order.
If user B do stuff like : select Cheese,select Butter, deselect Butter, select Milk , select Butter->then Cheese,Milk,Butter will be sent to servlet with this order.
Appreciate.
Check the fiddle for the checkbox order here
I used the following JS Code
checkedOrder = []
inputList = document.getElementsByTagName('input')
for(var i=0;i<inputList.length;i++) {
if(inputList[i].type === 'checkbox') {
inputList[i].onclick = function() {
if (this.checked) {
checkedOrder.push(this.value)
} else {
checkedOrder.splice(checkedOrder.indexOf(this.value),1)
}
console.log(checkedOrder)
}
}
}
Make a global variable to track the order:
var selectOrder = 0;
Bind this function to your onclick event in your inputs:
function onClickHandler() {
var senderId = this.id;
selectOrder = selectOrder + 1;
document.getElementById(senderId).setAttribute('data-order', selectOrder);
}
That will set a data-* (custom) attribute on each one with the order they were checked. So, when you submit your form, you can grab all of the checkboxes and get the order with .getAttribute('data-order'); Don't forget to reset your selectOrder = 0 when you submit so it will reorder them on the next time through.
Try this code.This works better
<html>
<head>
<title>My Page</title>
<script type="text/javascript">
var arr=new Array();
function fnc(myid)
{
if(document.getElementById(myid).checked == true)
{
arr.push(document.getElementById(myid).value);
alert(arr);
}
else
{
var item1=document.getElementById(myid).value;
for(i=0;i<2;i++)
{
if(arr[i]=item1)
{
found=i;
arr.splice(found,1);
}
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk" id="Milk" onchange="fnc(this.id)"> Milk<br>
<input type="checkbox" name="option2" value="Butter" id="Butter" onchange="fnc(this.id)"> Butter<br>
<input type="checkbox" name="option3" value="Cheese" id="Cheese" onchange="fnc(this.id)"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
Here, give this a try.
It maintains an array of all of the options' values, along with the order in which they were clicked. It handles the case where items are already checked when the page loads, by arbitrarily assigning them an increasing index for the order they were clicked in.
It handles items being unselected, it also can provide you with a little more info as a happy side-effect of the way I've done it. You can for instance get back values of 2, 3, 4 for selection order. If I load the page, then select Milk then cheese before unselecting then reselecting Butter, I get back the values 2,3,4 2,4,3 - I can straight away tell that the last selection made was Butter, and that it had previously been the first item selected. Likely useless, but an interesting consequence to me all the same.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv
{
border: 1px solid black;
display: inline-block;
}
</style>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var i, inputList = document.getElementsByTagName('input'), n = inputList.length;
var cbCount = 0;
var curOrder = 0;
for (i=0; i<n; i++)
{
if (inputList[i].type == 'checkbox')
{
cbCount++;
var cur = inputList[i];
cur.addEventListener('change', onCbChange, false);
var mObj = {val:cur.value, selOrder:0};
if (cur.checked)
{
mObj.selOrder = ++curOrder;
}
availOptions.push( mObj );
}
}
}
var availOptions = []; // an array to hold objects - { val, selOrder }
function getItem(value)
{
var i, n = availOptions.length;
for (i=0; i<n; i++)
{
if (availOptions[i].val == value)
return availOptions[i];
}
return null;
}
// just clear it's selOrder member
function mUnselect(value)
{
var Item = getItem(value);
Item.selOrder = 0;
}
// iterate through the list, find the highest value of selOrder, increment it and set this item's selOrder to that
function mSelect(value)
{
var i, n = availOptions.length;
var curMax=0;
for (i=0; i<n; i++)
{
if (availOptions[i].selOrder > curMax)
curMax = availOptions[i].selOrder;
}
curMax++;
getItem(value).selOrder = curMax;
}
function onCbChange()
{
if (this.checked)
mSelect(this.value);
else
mUnselect(this.value);
alert(this.value + ': ' + this.checked);
}
function showCurState()
{
var i, n=availOptions.length;
var mStr = '';
for (i=0; i<n; i++)
mStr += availOptions[i].val + ", selOrder: " + availOptions[i].selOrder + "\n"
alert(mStr);
}
</script>
</head>
<body>
<div id='myDiv' align="left">
<br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
<input type='button' onclick='showCurState();' value='Show state'/>
</div>
</body>
</html>