I have a JavaScript defined in my file as follows:
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport;
var httpTransport;
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https") {
httpsTransport="https";
} else if (splittedTransports[i]=="http") {
httpTransport="http";
}
}
</script>
And I would like to read it in my HTML page like:
<div class="checkbox">
<label class="checkbox inline">
<input type="checkbox" id="transport_http" name="transport_http" value="http" <%if(httpTransport=="http"){%>checked<%}%> />
</label>
<label class="checkbox inline">
<input type="checkbox" id="transport_https" name="transport_https" value="https" <%if(httpsTransport=="https"){%>checked<%}%>/>
</label>
</div>
But now I get an error that states:
org.mozilla.javascript.EcmaError: ReferenceError: "httpTransport" is not defined.
What am I doing wrong here?
I want to allow user to select an checkbox and save the form, and when he tries to edit the form, I want to show what he has saved in his previous operation.
So, when he tries to edit I try to read the values form backend and would like to show that particular option as checked.
<script language="javascript">
var transports = "<%=api.transports%>";
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
document.getElementById("transport_https").checked = true;
}else if (splittedTransports[i]=="http"){
document.getElementById("transport_http").checked = true;
}
}
</script>
HTML :
<div class="checkbox">
<label class="checkbox inline " >
<input type="checkbox" id="transport_http" name="transport_http" value="http" />
</label>
<label class="checkbox inline" >
<input type="checkbox" id="transport_https" name="transport_https" value="https"/>
</label>
</div>
The variables in your code are declared, but not defined.
Give them a random value first, and then update it with the if
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport = 'no';
var httpTransport = 'no';
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
httpsTransport="https";
}else if (splittedTransports[i]=="http"){
httpTransport="http";
}
}
</script>
Related
Im trying to make a bookshop website where the customer checks the books and writes the number of copies. But the code cannot tell if the checkbox is checked and goes with the "else" option always. What needs to change?
checkb1-5 are the checkboxes element
numbcop1-5 is the number of copies entered by the user
function Checker() {
var checkb1 = document.getElementById("adult");
if (checkb1.checked){
var numbcop1 = document.getElementById(numb1);
} else{
var numbcop1 = 0;
}
var checkb2 = document.getElementById("ado");
if (checkb2.checked){
var numbcop2 = document.getElementById(numb2);
} else{
var numbcop2 = 0;
}
var checkb3 = document.getElementById("child");
if (checkb3.checked){
var numbcop3 = document.getElementById(numb3);
} else {
var numbcop3 = 0;
}
var checkb4 = document.getElementById("school");
if (checkb4.checked){
var numbcop4 = document.getElementById(numb4);
} else {
var numbcop4 = 0;
}
var checkb5 = document.getElementById("transl");
if (checkb5.checked){
var numbcop5 = document.getElementById(numb5);
} else{
var numbcop5 = 0;
}
}
Looks like there are a few things to fix before to make your function works:
When you are doing var numbcop1 = document.getElementById(numb1); you need to make sure the parameter you are adding to getElementById is correct. E.g document.getElementById('numb1') or make sure that numb1 contains an string indicating the id for the function to look at e.g var numb1 = 'adult_amount'; and then use that variable as your code does document.getElementById(numb1)
Once you get the element that is expected to have the value, if it is an input you can do var numbcop1 = document.getElementById('numb1').value; to get the number typed by the user.
Let's refactor the Adult field to have a clear example on how it works:
<input type="checkbox" data-copies="adult_copies" id="adult">
<label>adult</label>
<input type="number" id="adult_copies">
And add this to your JS and check how the values comes using a single function that can be reused for the other books:
function getChecked(event) {
let numbcop;
let copies_id = event.target.getAttribute('data-copies');
if (event.target.checked){
numbcop = document.getElementById(copies_id).value;
} else{
numbcop = 0;
}
console.log(numbcop);
}
let adult = document.getElementById("adult");
adult.addEventListener('click', getChecked);
LMK if this works for your implementation.
actually it is going with the if option not else but it is returning zero.
You must point to the value of the numb1 not just the element.
for example:
var numbcop1 = document.getElementById(numb1).value;
at least this must be coded like this (?):
var
t_elem = ['adult', 'ado', 'child','school', 'transl'],
numbcop1 = 0,
numbcop2 = 0,
numbcop3 = 0,
numbcop4 = 0,
numbcop5 = 0
;
function Checker() {
t_elem.forEach((elm,idx)=>{
window['numbcop'+(idx+1)] = (document.getElementById(elm).checked) ? document.getElementById('numb'+(idx+1)).value : 0;
})
}
Get_Books.onclick = function() {
Checker();
console.log(numbcop1, numbcop2, numbcop3, numbcop4, numbcop5);
}
label { float:left; clear: both; display:block; width:80px; margin:10px 5px; text-align: right }
input, button { float:left; display:block; margin:10px 5px }
button { clear: both }
<label for="adult">adult: </label>
<input id="adult" type="checkbox" />
<input id="numb1" type="number" value="1" />
<label for="ado">ado: </label>
<input id="ado" type="checkbox" />
<input id="numb2" type="number" value="2" />
<label for="adult">child: </label>
<input id="child" type="checkbox" />
<input id="numb3" type="number" value="3" />
<label for="school">school: </label>
<input id="school" type="checkbox" />
<input id="numb4" type="number" value="4" />
<label for="transl">transl: </label>
<input id="transl" type="checkbox" />
<input id="numb5" type="number" value="5" />
<button id="Get_Books">Books</button>
Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>
I have a Magento website and there are some delivery options when ordering a product.
There are 2 methods available.
- pick up yourself
- deliver
When you choose radiobutton "deliver" some div with a textarea is visible.
This textarea needs to be required.
But when you select radiobutton "pick up yourself" the textarea is invisible and needs to be NOT required anymore.
I made a fiddle of the items
Can anyone help me with how to do this?
HTML:
<h2>Select delivery method</h2>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method"> pick up
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method"> deliver
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
If you are after a pure js version you can use this method:
function check() {
var items = document.getElementsByName('shipping_method');
var v = null;
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
v = items[i].value;
break;
}
}
var required = (v == "tablerate_bestway");
document.getElementById("deliv-hold").style.display = required ? "block" : "none";
if (required) {
document.getElementById("shipping_arrival_comments").setAttribute("required", true);
} else {
document.getElementById("shipping_arrival_comments").removeAttribute("required");
}
}
http://jsfiddle.net/gv7xh4cg/9/
Basically, iterate over items of the same name and see if they are selected, if they are grab the value from it and use that to show or hide the comments div.
Cheers,
Ian
Here you can see an example of code to do so :
$(document).ready(function() {
var submitMessage = "";
$(":radio").change(function() {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
$("#deliv-hold").hide(250);
}
else {
$("#deliv-hold").show(250);
}
});
$("form").submit(function(e) {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
submitMessage = "Your command is in process. Thank you for purshasing.";
}
else {
if ($("#shipping_arrival_comments").val().length < 1) {
e.preventDefault();
alert("Field 'delivery date and time' missing.");
submitMessage = "";
}
else {
submitMessage = "Deliver is on his way. Thank you for purshasing.";
}
}
if (submitMessage != "") {
alert(submitMessage);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Test check </title>
<meta charset = "utf-8" />
</head>
<body>
<span>Choose your delivery method :</span>
<form>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method">
<label for="s_method_freeshipping_freeshipping">Pick up yourself</label>
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method">
<label for="s_method_tablerate_bestway">Deliver</label>
<br />
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
<input type = "submit" id="submit_delivery" name = "submit_delivery" />
</form>
</body>
</html>
I used JQuery include (see below the code the script include) to use the DOM selector which is easier to use than plain javascript.
I updated your fiddle (it also makes the textarea required):
http://jsfiddle.net/gv7xh4cg/4/
You should include jQuery for:
$('input.radio').click(function(){
var selectedOption = $(this).val();
var delivlHold = $('#deliv-hold'),
comments = $('#shipping_arrival_comments');
if(selectedOption === 'freeshipping_freeshipping') {
delivlHold.show();
comments.prop('required',true);
} else {
delivlHold.hide();
comments.prop('required',false);
}
});
and than add display: none:
#deliv-hold{padding-top:20px; display: none}
It does what you asked for.
Why I'm getting undefined error in Firefox and IE. This code works well in Google Chrome. Here is the full code http://liveweave.com/fUhpiI
this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
<div>
<h2>1. Which one do you prefer?</h2>
<div>
<input type="radio" name="q1" id="radio1" class="radio" value="9"/>
<label for="radio1">Tea</label>
</div>
<div>
<input type="radio" name="q1" id="radio2" class="radio" value="4"/>
<label for="radio2">Coffee</label>
</div>
<div>
<input type="radio" name="q1" id="radio3" class="radio" value="1"/>
<label for="radio3">Milk</label>
</div>
</div>
<div>
</br>
<div><div>
<button type="button" onclick="hp(this.form)">Check</button>
<input class="reset" type="reset" value="Reset">
</div></div></div>
</form>
<div id="result"></div>
<div id="total"></div>
</body>
</html>
this is javascript
function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}
you should declare a answer variable .and you should access "q1" elements by giving index since you have 3 "q1" elements .basically form.q1 is a object NodeList .you can't get value from object NodeList.so actually in your case you should add brake to for loop and find the clicked radio button index .
you should use
answer1 = form.q1[i].value;
instead of
answer1 = form.q1.value;
explain
form.q1 is a object NodeList so
form.q1.value --> undefined since object NodeList/collection has no property "value"
and
form.q1[0] --> HTMLInputElement so
form.q1[0].value --> is not undefined
fixed code .WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/
function hp(form) {
var i;
var answer;
var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;
for (i = 0; i < 3; i++) {
if (form.q1[i].checked === true) {
count1++;
break;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
answer1 = form.q1[i].value; //error was here .
a = Math.floor(answer1);
document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}
if it worked in google chorm that's because browsers ignore some errors.
I am new to Javascript so I'm not sure if my code is working as I'm not sure how to test or run it. What I want my code to do is display the JSON created from gathering all the checked boxes. I haven't added a console.log anywhere because I'm not sure where it would be appropriate. I feel as though I have all the pieces but I am not sure how to put everything together.
The expected output should be:
{
"testpages" : [...data...],
"configs" : [...data...]
}
My code
<script type="text/javascript">
function grabSelected() {
var configs = [];
var testPages = [];
var selectedConfigs = document.getElementByClassName('.testpages').value;
var selectedTestPages = document.getElementByClassName('.configs').value;
for (var i = 0; i < selectedConfigs.length; i++) {
if (selectedConfigs[i].checked) {
configs.push(selectedConfigs[i])
}
}
for (var i = 0; i < selectedTestPages.length; i++) {
if (selectedTestPages[i].checked) {
testPages.push(selectedTestPages[i])
}
}
var jsonString = {"testpages" : testpages, "configs" : configs};
var testJson = JSON.stringify(jsonString);
}
</script>
<body class="wrap">
<form action="POST" >
<div class="testpages" id="left_col">
<input id="tp1" type="checkbox" value="1">Test Page 1<br>
...
...
<input id="tp30" type="checkbox" value="30">Test Page 30<br>
</div>
<div class="configs" id="right_col">
<input id="config_0" type="checkbox" value="Windows XP internet explorer 8">Windows XP
...
...
<input id="config_59" type="checkbox" value="OS X 10.9 Safari 7">OS X 10.9 Safari 7<br>
</div>
</form>
<input id="" type="submit" value="Submit" onclick="grabSelected();" />
</body>
<html>
Some of the (trivial) mistakes found in your original code:
Used getElementByClassName instead of getElementsByClassName
Used testpages instead of testPages in jsonString formation
Used the classnames testpages and configs for parent div instead of
input elements.
Here's the one you can use:
<html>
<script type="text/javascript">
function grabSelected() {
var configs = [];
var testPages = [];
var selectedConfigs = document.getElementsByClassName('testpages');
var selectedTestPages = document.getElementsByClassName('configs');
for (var i = 0; i < selectedConfigs.length; i++) {
if (selectedConfigs[i].checked) {
configs.push(selectedConfigs[i].value)
}
}
for (var i = 0; i < selectedTestPages.length; i++) {
if (selectedTestPages[i].checked) {
testPages.push(selectedTestPages[i].value)
}
}
var jsonString = {"testpages" : testPages, "configs" : configs};
var testJson = JSON.stringify(jsonString);
}
</script>
<body class="wrap">
<form action="POST" >
<div id="left_col">
<input class="testpages" id="tp1" type="checkbox" value="1">Test Page 1<br>
<input class="testpages" id="tp30" type="checkbox" value="30">Test Page 30<br>
</div>
<div id="right_col">
<input class="configs" id="config_0" type="checkbox" value="Windows XP internet explorer 8">Windows XP
<input class="configs" id="config_59" type="checkbox" value="OS X 10.9 Safari 7">OS X 10.9 Safari 7<br>
</div>
</form>
<input id="" type="submit" value="Submit" onclick="grabSelected();" />
</body>
<html>
I believe the problem is that you're trying to return the value of the class instead of checking to see if is checked. Instead of getElementByClassName().value, try getElementByClassName(id).getElementsByTag('input'). This will return an array that you can loop through and return the values for.
Apologies for answer formatting, typed from SO app.