2

I am trying to get the checked value in checkbox and display it in some specific format using javascript but somehow I dont know how to do it

I have tried html and javascript and I dont know ajax or jquery so I am trying javascript only

function Hobby() { var checkedValue = null; var inputElements = document.getElementsByClass('messageCheckbox'); for(var i=0; inputElements[i]; ++i){ if(inputElements[i].checked){ checkedValue = inputElements[i].value document.getElementById("hobbies_value").innerHTML = inputElements; break; } } }
 Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting <input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing <input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports <input type="button" value="student_submit" onclick="Hobby()"><br/>

If checked values are dancing and painting

then output should be

Hobby:#dancing#painting

and I dont want to display it as alert box instead I want to display it on same page

6
  • You hava a typo. It should be getElementsByClassName Commented Feb 13, 2019 at 16:59
  • Still not working and what about the format in which i want Commented Feb 13, 2019 at 17:01
  • Possible duplicate of Get the value of checked checkbox? Commented Feb 13, 2019 at 17:03
  • this is not duplicate that question was using ajax and also alert box or else i wouldnt have posted the question and you can visit whole internet but none of them is clearly stating how to print the checked value in check box Commented Feb 13, 2019 at 17:06
  • They aren't using ajax, and that link answers your question. There are many answers in that link that help you actually. The code will not be same of course because its a different project, but how to get it done is the same. Commented Feb 13, 2019 at 17:09

1 Answer 1

2

You need to concatenate the values and display them outside the loop. Something like this:

function Hobby() { var checkedValue = ""; var inputElements = document.getElementsByClassName('messageCheckbox'); for(var i=0; inputElements[i]; ++i){ if(inputElements[i].checked){ checkedValue += "#"+inputElements[i].value } } document.getElementById("hobbies_value").innerHTML = checkedValue; }
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting <input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing <input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports <input type="button" value="student_submit" onclick="Hobby()"><br/> Javascript code is <div id="hobbies_value"></div> 

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.