creating a for-loop using Javascript? - javascript

I have a problem creating a for-loop using Javascript. It seems everyting is fine for me but still I didn't get what I want.
Take a look please to this code to understand more:
The HTML form code:
<form name="myform">
<textarea name="inputtext" cols="100%" rows="10%"></textarea><br />
<input type="radio" name="options" value="javascript" checked> Option1 <br />
<input type="radio" name="options" value="windows"> Option2<br />
<input type="button" value="Do it" onClick="generate();"><br />
<textarea name="outputtext" cols="100%" rows="10%"></textarea><br />
</form>
The Javascript code:
function generate() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
for(int i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
The problem is not clear for me.
However, when I try to comment out the for-loop, everything works fine !
Any ideas?

There is no int data type in Javascript (or any data types at all used to declare variables).
for(var i=0; i<code.length; i++) {

There is also an Object-oriented solution to this.
var generate = {
loop: function() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
//CHANGE THE INT(I assume Java) DATATYPE TO A LOCAL VARIABLE USING THE var KEYWORD TO KEEP THE SCOPE IN THE FOR LOOP
//RECURSION CAN BE QUICKER
for(var i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
generate.loop();

Related

Javascript: Triggering "for" loop using "if...else" statements not working

I am trying to make a simple script which automatically blocks the input boxes in the file when I tick a checkbox.
For this, I am trying to add/remove the "disabled" attribute by triggering a loop every time the checkbox is clicked. Looks something like this:
function locker() {
var boxes = document.querySelectorAll("input[type='text']");
var x = getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
boxes[i].disabled = true;
} else {
boxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
However, I can't seem to get it to work. I don't have much experience coding, and I feel like I am making a very basic mistake, but I couldn't find a solution to this problem so far... How can I solve this? Are there any other workarounds to get the same result?
Thanks in advance
You need to use document.getElementById("lock") instead of getElementById("lock") and use the correct variable names for your variables. You used inputBoxes and boxes while you meant to use the same variable.
function locker() {
var inputBoxes = document.querySelectorAll("input[type='text']");
var x = document.getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
inputBoxes[i].disabled = true;
} else {
inputBoxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>

Re-feeding a variable into a looped function

I'm attempting to make a simple program for encoding things in base64 multiple times (not really for any particular reason, just more as an example and practice). I've been having quite a bit of trouble though, it could be because I've not had enough (or possibly had too much) coffee.
I can't seem to figure out how to refeed my variable (text) back into the function that encodes it until i is equal to times
Any assistance with this would be appreciated!
<html>
<head>
<script>
function encodeThis(text,times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
</script>
</head>
<body>
<b>Text to Encode</b><br/>
<input type="text" id="encode"><br/>
<b>Number of Times to Encode (Integers Only)<br/>
<input type="text" id="times">
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">
</body>
</html>
Would I need to put a function inside of that function to refeed the variable in?
You need to assign the result of the encoding back to the variable.
function encodeThis(text, times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
But in terms of the overall code in your example you also need to actually get the text from the #encode and the #times elements and fix the syntax error in the for loop.
So
function encodeThis(text, times) {
var toEncode = text.value, // read the value from the encode input element
numTimes = parseInt(times.value, 10); // read the value from the times element and convert to number
for (var i = 0; i < numTimes; i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
<b>Text to Encode</b><br/>
<input type="text" id="encode" /><br/>
<b>Number of Times to Encode (Integers Only)</b><br/>
<input type="text" id="times" />
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">

Get array text filed value via javascript

in my process text filed in array i need to get the value via javascript but my code is not working my code following
<input type="text" id="itemid[]" name="itemid[]" class="span12"/>
and javascript code is
function getstock()
{
var itemidarr=document.getElementById('itemid[]');
if(itemidarr!= null)
{
alert(itemidarr.length);
}
}
any other solution for this
The IDs can't contain brackets, these: [], so:
<input type="text" id="itemid1" name="itemname1" class="span12"/>
<input type="text" id="itemid2" name="itemname1" class="span12"/>
<input type="text" id="itemid3" name="itemname1" class="span12"/>
Then you have to loop through the IDs:
function getstock()
{
for(var i=1; i<=3; i++){
var itemidarr=document.getElementById("itemid"+i);
if(itemidarr!= null) alert(itemidarr.length);
}
}
The id attribute here cannot contain [ ].
Put your textboxex in "fieldset tag"
Like:
<fieldset id="field">
//Put you text boxes here<input type='text'>
</fieldset>
Access these by:
document.getElementById("list....").getElementsByTagName("input")[indexoftext];
indexoftext is the text box you wan to choose.
Hope it helps!
you can try something like this below
<input type="text" id="itemid" name="itemid" class="span12"/>
function getstock()
{
var itemidarr = document.getElementsByName('itemid');
for(var i = 0; i < itemidarr.length; i++){
var item=document.getElementsByName('itemid')[i].value;
if(item!= null)
{
alert(item);
}
}
}
You can't make an array to fill in an input text, only for input like radio or checkbox.
Text input only accept a single string.
function getstock() {
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
can u use this code
i got the result
function getstock1()
{
alert("test");
var itemidarr = document.getElementsByName('itemid[]');
for (var i = 0; i < itemidarr.length; i++)
{
alert(itemidarr[i].value);
}

Using javascript to check if a radio button is selected and return a specific answer based on the selection

I am looking, in the cleanest way possible to be able to take a simple yes or no question and test for which answer has been chosen.
For instance in this case if a "yes" I want it to return a value of "Continue" into a specified area (a 3 column table which has a question in the first, the radio buttons in the second, and I want it to update and display the answer in the third).
My code for the JS stands thus far:
<script type="text/javascript">
var answer = 'place-holder';
var user_input;
function checkForm()
{
var substanceab = document.getElementById('Sub');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab.length[i].checked)
{
user_input = substanceab.length[i].value;
}
}
if (user_input ="yes")
{
return answer = "Continue";
}
else if (user_input ="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm[user_input];
};
</script>
and the Body text (minus the actual question):
<table class="table table-bordered">
<tr>
<td width="58%"><center><strong>Required:</strong></center></td>
<td width="19%"></td>
<td width="23%"><center><u><strong>___________</strong></u></center></td>
</tr>
<tr>
<td> <span class="sub depend"> <strong><i>_________</i> </strong></span></td>
<td> <span class="sub depend ans">
<form name="Substance">
<label class="radio inline">
<input type="radio" value="yes" name="substance" onclick="writeAns()">
yes </label>
<label class="radio inline">
<input type="radio" value="no" name="substance" onclick="writeAns()">
no </label> </form></span></td>
<div id="answerwrite"></div>
<script type="text/javascript">
document.write("<td>" + writeAns() + "</td>")
</script>
</tr></table>
Ok, fixed the 'funk' but like I said, more used to java than javascript, completely tougher syntax. I agree, I only used the ID thing to try and get this to work with a different method, but it never did. Now with some of the suggestions it is just giving me undefined everywhere. And while I agree this will eventually turn to jquery, I have NO clue how to work with it, hence figuring out this in javascript first.
A few things:
document.getElementByID()
will always return the first element, as ID's are supposed to be unique.
Instead, use:
document.getElementsByName('substance');
Next, in your loop, you are improperly referencing the array's members using the .length property. Try this instead:
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
Finally, in javascript, the '=' opertator is always an assignment statement. To do comparisons, always use '==':
if (user_input == "yes")
{
return answer = "Continue";
}
else if (user_input =="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
Also, try to avoid global variables whenever possible.
Here is the working code, refactored a bit:
<input type="radio" value="no" id= "Sub" name="substance" onclick="writeAns()">
function checkForm()
{
var user_input;
var substanceab = document.getElementsByName('substance');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
if (user_input == "yes")
{
return "Continue";
}
else if (user_input =="no")
{
return "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm();
};
Very easy if you are using JQuery.
Ensure your elements have the same "name" attribute and use:
var RadioGroupResult = $('input[name="MyRadioGroupNameHere"]:checked').val();
Nice and simple.

How to retrieve the value from a radio button in javascript?

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

Categories

Resources