getElementById not returning element - javascript

I am trying to get an elements id from another elements value and I just keeps returning null. Clicking on the first check box should show what the issue is that I am having.
<input id="test" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="66" />
<input id="rrrr66" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="33" />
<script>
function checkAddress(checkbox) {
if (checkbox.checked) {
var testing = '"rrrr'+document.getElementById("test").value+'"';
alert(typeof testing); **<-- shows the correct type**
alert(testing); **<-- shows the correct value**
alert(document.getElementById(testing)); **<-- does not work**
alert(document.getElementById("rrrr66")); **<--works**
}
}
Demo Of issue

Remove the quotation marks from the string:
var testing = 'rrrr'+document.getElementById("test").value;
Quotation marks are for the parser to indicate a string literal. The quotation marks are not actually part of the value. What you are currently doing is equivalent with
document.getElementById('"rrrr66"')
Compare these two outputs:
console.log("foo bar"); // foo bar
console.log('"foo' + ' bar"'); // "foo bar"

1
Get the value of test and add rrrr before:
var testing = "rrrr"+document.getElementById("test").value;
2 Do the trick
document.getElementById(testing)
This should work.

Related

How to get the first and second word from a string in jquery?

I have a checkbox having value attribute as shown below :
<input type="checkbox" class="skis checkbox" name="skis" value="hi?hello?Good">
When I am clicking this particular checkbox i want to get the value of this checkbox separately in three different JavaScript variables as hi, hello, Good and should check with ? delimiter in jQuery. Can anyone say how to do this in JavaScript ?
You don't need jQuery for this. To split the string, you can just use .split() function with the parameter being the question mark. All the values will be stored as an array and you can access the first two words using the array index.
$(function () {
$("input").click(function () {
var values = this.value.split("?");
console.log("First word: " + values[0]);
console.log("Second word: " + values[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="skis checkbox" name="skis" value="hi?hello?Good">
Use this javascript code.
$(function(){
$('input.checkbox').on('click',function(){
var val=this.value.split('?');
var first=val[0];
var second=val[1];
var third=val[2];
debugger;
});
});
Use .split function to split string on every delimiter:
<input
type="checkbox"
class="skis checkbox"
name="skis"
value="hi?hello?Good"
onClick="console.log(this.value.split('?'))"
/>

Assigning two values to a checkbox javascript

I need to pass two different values back as the result from one checkbox. I tried an object, but the result was undefined (the code works with one value).
' <input type="checkbox" id="cat" value="'+{value1: data.blue, value2: data.red} +'"/>'
result.value1 is always undefined, whereas result works for just a string.
What is the best way to do this using javascript/jquery.
You can use attr for add more values, for example:
<input type="checkbox" id="cat" data-value1="blue" data-value2="red" value=""/>
Get values using jQuery, use:
$("#cat").data("value1");//return 'blue'
$("#cat").data("value2");//return 'red'
Result: https://jsfiddle.net/cmedina/a0ya5bwp/
Why not create a string with a separator
Something like
value1 \t value2
And you just have to search for this separator and cut the string to get your 2 differents values?
You can stringify the object and put that value on the input as a data attribute, in the input change handler, parse the string to JSON.
HTML
<input type="checkbox" id="cat" name="cat">
<label for="cat">Cat</label>
Javascript
var input = document.getElementById('cat');
var testValue = {value1: 'blue', value2: 'red'};
input.setAttribute('data-value',JSON.stringify(testValue));
input.addEventListener('change', function(event) {
var inputValue = JSON.parse(event.target.getAttribute('data-value'));
console.log(inputValue);
});
Demo : JSFiddle
it looks like you have a spelling mistake : vaule1 should be value1

Adding Substring to Input

I'm trying to add coordinates to a input text after trimming characters from each end of the string. But for some reason my trimming part isn't working. Can anyone help me out here? I'd really appreciate it.
Here's my code:
<input type="hidden" id="latlng" onload="getFinal()">
<script>
function getFinal(){
var input = document.getElementById('latlng').value;
consolelog(input);
var last = (input.length)-1;
var final = input.substring(1,last);
document.getElementById('final').value = final;
}
</script>
<input type='hidden' id='final'>
::: EDIT :::
I've tried simplifying things because the value that needs to be trimmed is in the rest of the code. But for some reason, when I use the code below, it still won't put the value in the text box.
var final = pos.substring(1,(pos.length)-1);
document.getElementById("final").value = final;
Now I'm getting the error: TypeError: Cannot set property 'value' of null at :4:44
OnLoad should not work for input. You better write as a simple javascript block
<input type="hidden" id="latlng" onload="getFinal()" />
<input type='hidden' id='final' />
<script>
var input = document.getElementById('latlng').value;
consolelog(input);
var last = (input.length)-1;
var final = input.substring(1,last);
document.getElementById('final').value = final;
</script>

Hide and show another element onclick of a radio button, based on value

I have 4 jquery radio buttons in my form something like this
<form:radiobutton path="lcmoption" name ="lcmoptions" id ="lock" value="lock" checked="checked"/>
<fmt:message key="lcm.form.options.lock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="unlock" value= "unlock"/>
<fmt:message key="lcm.form.options.unlock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="terminate" value="terminate" />
<fmt:message key="lcm.form.options.terminate" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="wipe" value="wipe" />
<fmt:message key="lcm.form.options.wipe" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="other" value="other" />
<fmt:message key="lcm.form.options.other" />
onclick of the first four radio buttons I am dynamically loading the select box using an AJAX call. When the user clicks the last option, i.e, other, I need to hide the textbox and show a text area.
I tried using:
$("input:radio[name=lcmoption]").click(function() {
if(type=="other")
{
$([name="reasonsList"]).css("display",none");
$([name="otherreasonsList"]).css("display", "block");
}
else
{
// AJAX CALL to load dropdown (for other options)
}
}
But this did not work. I also tried:
$([name="reasonsList"]).hide();
$([name="otherreasonsList"]).show();
This shows both the dropdown and text area. Can anyone help me on hiding reasonsList div and show otherreasonsList div onclick of a radio button with other value?
There's all kinds of syntax errors in the code you posted.
For instance, you need to quote your selector strings as text, and an attribute value in an attribute selector ([name=something]) can be either an unquoted single word or a quoted string.
In this case, just leave it out:
$('[name=reasonsList]').show();
Also, instead of $.click(), I would use $.change(), which will detect when the radio value has changed.
$("input:radio[name=lcmoptions]").change(function(){...});
See notes in comments:
// First line looks ok, but I would use a .change() handler
// Also, I just noticed you're:
// "input:radio[name=lcmoption]"
//
// But shouldn't it be:
// "input:radio[name=lcmoptions]"
//
// See lcmoptions vs lcmoption (no s on second); it's lcmoptions
// in your template code. I don't know what path="lcmoption" means,
// but I think name="lcmoptions" is what you need to use to select.
$("input:radio[name=lcmoption]").click(function() {
// What is type? I think you mean this.value or $(this).val()
// Don't forget to lowercase the comparison, so other matches
// Other.
if (this.value.toLowerCase() == "other")
{
// The selector needs to be quoted as a string, ie:
// '[name="reasonsList"]'
//
// Also, jQuery has a shortcut method, $(sel).hide();
$([name="reasonsList"]).hide();
// The same thing here, you need to quote that string or
// alternatively, since it's a single word, leave the quotes
// out of the selector, ie:
// $('[name=otherreasonsList]')
//
// Again, jQuery has a shortcut method, $(sel).show();
$('[name=otherreasonsList]').show();
}
// Don't know if you missed this in the example, but you need });
// to close the $.click() function.
});
And your second attempt:
// Same problem as above, you need to quote the string for the
// selector, ie:
// $('[name=reasonsList]')
//
// With inner quotes, but here they're unnecessary.
$('[name="reasonsList"]').hide();
//
// Without inner quotes on name value
$('[name=otherreasonsList]').show();
For what you're wanting to do, you can:
$(document).ready(function(){
// This is called caching, which is a good practice to get
// get into, as unless you need to requery due to dynamic
// changes, selecting them only once and reusing will give
// you better performance.
var $lcmoptions = $('input:radio[name=lcmoptions]'),
$textbox = $('[name=textbox]'),
$textarea = $('[name=textarea]');
$lcmoptions.change(function(){
// Note I this.value.toLowerCase() the comparison value
if (this.value.toLowerCase() === 'other') {
$textbox.hide();
$textarea.val($textbox.val()).show();
} else {
$textarea.hide();
$textbox.val($textarea.val()).show();
}
});
});
For more information on caching, see:
Does using $this instead of $(this) provide a performance enhancement?
This is assuming your client-side markup looks something like:
<input type="radio" name="lcmoptions" id="unlock" value= "lock"/> Lock
<input type="radio" name="lcmoptions" id="unlock" value= "unlock"/> Unlock
<input type="radio" name="lcmoptions" id="terminate" value="terminate" /> Terminate
<input type="radio" name="lcmoptions" id="wipe" value="wipe" /> Wipe
<input type="radio" name="lcmoptions" id="other" value="other" /> Other
<div>
Enter text:
<input type="text" name="textbox" value="test text stuff"/>
<textarea name="textarea"></textarea>
</div>
http://jsfiddle.net/LthAs/
Have tried this mine working fine
if(document.getElementById('other').checked==true)
{
$("#txtboxID").hide(350);
$("#txtareaid").show(350);
}
try this, u can put this on change event or click event.
if ($("radio[#name='lcmoptions']:checked").val() == 'other')
$("#otherreasonsList").show();

Javascript returning 'undefined' if i have less than one element in the form.

In the following example:
<html>
<head>
<SCRIPT language="JavaScript">
function checkcheckboxElem(checkboxElem)
{
alert ("checkboxElem " + checkboxElem.length);
}
</script>
</head>
<body>
<form name="checkForm">
Master: <input type="checkbox" name="master" value="6694" onclick="checkcheckboxElem(document.checkForm.checkboxElem)"><br>
Child1: <input type="checkbox" name="checkboxElem" value="2">
</form>
</body>
The alert outputs 'undefined'. For some reason it does this if there is only one checkbox. If i add another checkbox then it outputs the correct length. If i change it as shown below then it outputs 2
<html>
<head>
<SCRIPT language="JavaScript">
function checkcheckboxElem(checkboxElem)
{
alert ("checkboxElem " + checkboxElem.length);
}
</script>
</head>
<body>
<form name="checkForm">
Master: <input type="checkbox" name="master" value="6694" onclick="checkcheckboxElem(document.checkForm.checkboxElem)"><br>
Child1: <input type="checkbox" name="checkboxElem" value="2">
Child2: <input type="checkbox" name="checkboxElem" value="1">
</form>
Why does it return 'undefined' if it is only one checkbox?
Thanks
In the first case document.checkForm.checkboxElem refers to a single input element, in the second case it refers to an array of input elements. You could do:
function checkcheckboxElem(checkboxElem) {
if(!checkboxElem.length)
checkboxElem = [checkboxElem];
alert ("checkboxElem " + checkboxElem.length);
}
It returns undefined because there is only a single element - javascript does not treat this as an array so it has no length property .... you could use this to ensure you always have a length :
var len = checkboxElem.length;
if(len == undefined) len = 1;
In the first case it reffers directly to the checkbox element and it has no length property. In the second case, there are multiple elements with the same name, so it returns an array of corresponding elements.
To get array of elements use
document.getElementsByName('checkboxElem');
It returns the number of elements found, instead of the value of one..
The output 2 isn't the value of one of the boxes.. It's the amount of elements..
use something like checkboxElem.val()
beacuse in first case
document.checkForm.checkboxElem
is specific element, but if there are more elements with same name it is array - try this
alert ("checkboxElem " + ( typeof( checkboxElm.length ) == 'undefined' ? 1 : checkboxElem.length ));

Categories

Resources