control radio button from textfield value - javascript

everyone..i want after i type "0203-ED" in textfield ...two character behind that text can control the radio button.. "ED" character from that text can make one radiobutton which has value="ED" are checked...
this is my code:
<script type="text/javascript">
var model=$("#tags1").val();
var version[0,0]="JD";
var version[0,1]="87.5-107.9";
var version[1,0]="ED";
var version[1,1]="87.5-108.0";
var version[2,0]="EED";
var version[2,1]="65.0-74.0";
// each version
for (var i = 0; i < version.length; i ++) {
if (model.lastIndexOf(version[i,0])!=-1) {
$("#value").replaceWith("<div id='value'>"+version[i,1]+"</div>");
} else {
$("#value").replaceWith("<div id='value'></div>")
}
// end each
}
</script>
what's wrong with my code??

I see a couple things going on.
First, why do you have a default: in there? That's a keyword used in switch statements; it's not valid in an if statement. Remove it entirely.
You also have model,lastIndexOf instead of model.lastIndexOf

you don't have to use .replaceWith()...
for (var i = 0; i < version.length; i ++) {
if (model.lastIndexOf(version[i,0])!=-1) {
$("#value").html(version[i,1]);
} else {
//default
$("#value").html("");
}
// end each
}

Watch your language typing. It should be text/javascript. Right now you have text/jaavascript. Depending on the browser and your doctype, this could prevent your script from even executing (it wouldn't just fail silently, it wouldn't even get the chance to fail).
In addition to the answers already given, try declaring your array only once. There are several ways create the data structure you're after. Use whichever style you find most comfortable.
var version = [['JD',"87.5-107.9"],["ED","87.5-108.0"],["EED","65.0-74.0"]];
var version = [];
version[0] = ["JD","87.5-107.9"]
version[1] = ["ED","87.5-108.0"];
version[2] = ["EED","65.0-74.0"];
var version = [];
version[0] = [];
version[0,0]="JD";
version[0,1]="87.5-107.9";
version[1] = [];
version[1,0]="ED";
version[1,1]="87.5-108.0";
version[2] = [];
version[2,0]="EED";
version[2,1]="65.0-74.0";
About the third version, though, I'm actually not sure that your array notation (version[0,1]) is universally supported. I don't think I've seen anyone use that notation in more than 10 years. Typically, you access members of a multi-dimensional array with the notation: myArray[x][y]. But maybe that's just a style difference. I'm not sure.
[EDIT] Are you trying to do something like this? This isn't terribly efficient, but it may be a starting point for you. In this case, jQuery is definitely your friend.
<input type="radio" name="version" value="87.5-107.9" /><label class="version">JD</label><br />
<input type="radio" name="version" value="87.5-108.0" /><label class="version">ED</label><br />
<input type="radio" name="version" value="65.0-74.0" /><label class="version">EED</label><br />
<input type="text" name="version_text" value="Enter your value" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">//<![[
var jVersionTextInput = $('input[name=version_text]');
var jLabels = $('label.version');
var jRadioButtons = $('input[name=version]');
var intVersionCount = jLabels.size();
var updateRadioButtons = function() {
var rxLabelValue;
var isValueFound = false;
rxLabelValue = new RegExp( $(jVersionTextInput).val() );
for (var i = 0; i < intVersionCount; i++) {
if (!isValueFound && rxLabelValue.test($(jLabels[i]).html())) {
jRadioButtons[i].checked = true;
isValueFound = true;
}
else {
jRadioButtons[i].checked = false;
}
}
}
jVersionTextInput.keyup(updateRadioButtons);
//]]></script>

Related

How do I use getElementById on dynamically created inputs?

I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!

Uncaught TypeError: Cannot set property 'innerHTML' of null error

I got error of Uncaught TypeError: Cannot set property 'innerHTML' of null for below script.
I added the script tags after the body. But still I get the error.
I want to show the text boxes in the same page within the div with the ID showTextBoxes.
Below is the HTML and JS.
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var a = document.writeln('<input type="text" name="Fname"><br/><br/>');
document.getElementById('showTextBoxes').innerHTML = a;
}
document.writeln('<input type="submit" name="submit">');
}
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
Actually document.write()and document.writeln() works in a different ways you think.
It actually clears all the document in your case you you are getting null.
See this
If you wanna add some element to your body you can use document.body.innerHTML += string.appendChild() can also be used but its not for stings
function showArray(){
var numofArr = parseInt(document.getElementById("numofArr").value);
for (let i = 0; i < numofArr; i++) {
var a = '<input type="text" name="Fname" /><br/><br/>'
document.getElementById('showTextBoxes').innerHTML += a;
}
document.body.innerHTML += '<input type="submit" name="submit"/>'
}
<body>
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
I think there are several ways, but I would recommend looking at append. Something like this should work:
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var textBox = document.createElement("input");
var enter = document.createElement("br");
document.getElementById('showTextBoxes').append( textBox );
document.getElementById('showTextBoxes').append( enter );
}
}
There are various places in your script which prevent it from running correctly. I'll address them step by step so you can follow along.
First of all, you should avoid inline event handlers in your HTML for the same reasons you should avoid inline style declarations. So don't use onclick=" ... " inside your HTML and instead add eventlisteners in your JS. This also gives you the ability to cancel the default behaviour or stop event propagation and such things.
Next thing is, you try to use the value of your numofArr input as upper bounds for your loop without casting it to a Number. Because <input> elements return their value as a String, this is very likely to fail. Besides, you should use the type="number" attribute instead of type="text" on that element. It's not required to do so, but just good measure.
OK, now for the showArray function:
Instead of using document.writeln (or document.write), create elements with document.createElement and add them to the DOM with appendChild.
You can see a working example below. Don't be confused by the byId and makeEl functions, they are just utilities so you don't have to write document.getElementById and document.createElement all the time.
// ====== UTILITY FUNCTIONS ======
function byId (id, root = document) {
return root.getElementById(id);
}
function makeEl (tag) {
return document.createElement(tag);
}
// ====== PROGRAM STUFF ======
function showArray (e) {
e.preventDefault();
let numofArr = parseInt(byId('numofArr').value, 10);
let output = byId('showTextBoxes');
for (let i = 0; i < numofArr; i++) {
let textIn = makeEl('input');
textIn.type = 'text';
textIn.name = 'Fname';
output.appendChild(textIn);
output.appendChild(makeEl('br'));
output.appendChild(makeEl('br'));
}
let submit2 = makeEl('input');
submit2.type = 'submit';
submit2.value = 'Submit';
document.body.appendChild(submit2);
}
byId('submit1').addEventListener('click', showArray, false);
<p>Number of arrays(array within 0-9)</p>
<input type="number" id="numofArr">
<input id="submit1" type="submit" value="Submit"><br><br>
<div id="showTextBoxes"></div>

Eloquent JS Exercise (Ch.18 Q. 2)

I was hoping someone can help me figure out what I'm doing wrong... There's this exercise in the Eloquent JS book that asks you to write some code that can suggest words/values to users as they type... The code I've written is below. What happens is that when I run the code, the div element's text content changes to the wrong value. Specifically, it's set to a string of all the elements inside the array 'terms'. I really cant figure out why this happens!
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
<script>
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i]);
div.appendChild(text)};
};
})
</script>
I guess you forgot to clean the div before each change in the input.
I also added a space after each word to make the output more readable.
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
div.innerHTML = '';
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i] + ' ');
div.appendChild(text)};
};
})
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
With this code, you will display the name of the properties from the window object that contains the last word from the input. Try it writting "window location document". Is it what you are looking for?

How to separate javascript and markup in case of a script line with parameters?

Separating javascript and markup is easy when the script doesn't have parameters. But how is it done with inline script lines that do? Example:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add"
onclick="showSelectTables('none','none','none','table','none','none')">
</td>
(....)
<script>
function showSelectTables(set1a,set1b,set1c,setSetup,set2,set3) {
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
.
I've tried all varieties I can think of, but all I'm getting is error reports, 'undefined' or the silent treatment from the browser. Is it possible at all, and if so, how? I would be looking for a vanilla javascript solution.
EDIT: see here for what I'm trying to achieve: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript, section 2.
I suggest you to change your HTML generation logic to generate the followings:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add" />
</td>
<script>
// just show 2 variables for demo
var settings = { change-add : { set1a: 'some_value', set1b: 'some_value' } }
$('#change-add').click(function() {
showSelectTables($(this).attr('id'));
});
function showSelectTables(the_id) {
var set1a = settings[the_id]['set1']; // which returns 'some_value'
// similar for set1b,set1c,setSetup,set2,set3
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
Note: this assumes you use jQuery.
An important note: there is nothing wrong to use inline onclick, but it's a better pattern to separate JS and HTML

Uncaught TypeError: Cannot read property 'checked' of null index.html:24

I'm newbie in JavaScript, i hope you can help me, as in topic, null property.
var add = document.getElementById('addition').checked;
var subs = document.getElementById('substraction').checked;
var multi = document.getElementById('multiplication').checked;
var div = document.getElementById('division').checked;
var result = 0;
var x = parseInt(document.getElementById('firstNumber').value);
var y = parseInt(document.getElementById('secondNumber').value);
function calculator()
{
if (add)
{
result = addition(x, y);
}
else if (subs)
{
result = substraction(x, y);
}
else if (multi)
{
result = multiplication(x, y);
}
else if (division)
{
result = division(x, y);
};
}
<fieldset>
<legend>Method</legend>
<p><label><input type="radio" name="method" id="addition" />Addition</label></p>
<p><label><input type="radio" name="method" id="substraction" />Substraction</label></p>
<p><label><input type="radio" name="method" id="multiplication" />Multiplication</label></p>
<p><label><input type="radio" name="method" id="division" />Division</label></p>
</fieldset>
<input type="submit" value="Submit" onclick="calculator();" />
And them i got message
"Uncaught TypeError: Cannot read property 'checked' of null index.html:24
(anonymous function)"
Please help me.
Greets!
Your javascript code is executing before the DOM elements are ready on the page.
You need to execute the code that is trying to get the inputs after the DOM is ready.
(function () {
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', domReady, false);
} else {
window.attachEvent('onload', domReady);
}
} ());
function domReady() {
var add = document.getElementById('addition').checked;
var subs = document.getElementById('substraction').checked;
var multi = document.getElementById('multiplication').checked;
var div = document.getElementById('division').checked;
var result = 0;
var x = parseInt(document.getElementById('firstNumber').value);
var y = parseInt(document.getElementById('secondNumber').value);
}
It seems like there are several issues going on here. There is probably more code somewhere? or more to be added. Anyways, I would go ahead and declare your variables when your function is actually called.
function calculator() {
var add = document.getElementById('addition').checked;
var subs = document.getElementById('substraction').checked;
var multi = document.getElementById('multiplication').checked;
var div = document.getElementById('division').checked;
var result = 0;
var x = parseInt(document.getElementById('firstNumber').value);
var y = parseInt(document.getElementById('secondNumber').value);
if (add) {
result = x + y;
}
else if (subs) {
result = x - y;
}
else if (multi) {
result = x * y;
}
else if (division) {
result = x / y;
alert("division");
}
}
I don't know if you are planning on using another method for division but if you want to divide the two numbers if the radio button of division was selected you'd just use /.
You could also use the event of a radio button being checked to set your add, subs, multi, div variables.
As Patrick Evans stated, you can't look for the value of your radio button before the radio buttons have been rendered (which we could do with $(document).ready() or as Patrick Evans showed. HOWEVER we probably do not want to look at their values until either the user selects one or your button is clicked.

Categories

Resources