Convert a string into a character array using JavaScript - javascript

Continue on my Javascript - Radio Button onChange
Here is my code:
<html>
<head>
<script type="text/javascript">
function Change(radio)
{
for(i = 1; i <=3; i++)
{
if(i == radio.value)
{
setvalue = "Y";
value = setvalue;
radiovalue = radio.value;
}
else
{
setvalue = "N";
value = setvalue;
radiovalue = radio.value;
}
ChangeValue(setvalue,value);
}
function ChangeValue(setvalue,value)
{
var getvalue = value;
document.write(getvalue);
}
}
</script>
</head>
<body>
<?php
for($i = 1; $i <= 3; $i++)
{
?>
<input type="radio" name="choice" value="<?php echo $i;?>" onchange="Change(this)" /><br />
<?php
}
?>
</body>
</html>
From the above code, if I clicked the first radio button, the output is YNN.
Now I want to separate the value with commas (YNN) and put the result into an array ("Y","N","N").
I wrote the following inside ChangeValue function:
function ChangeValue(setvalue, value)
{
var getvalue = value;
document.write(getvalue);
var seperate = new array();
seperate = getvalue.spilt(",");
}
However the above code doesn't put my value into array.
What am I doing wrong? Any solutions to solve this problem?

You have to split the string into separate chars as array.
var str = 'YNN'; //or whatever
var strWithComma = str.split(''); //to char array
After this you can join the chars to a new string for display output.
var str = 'YNN';
var strWithComma = str.split('').join(','); //'YNN' (string) --> ['Y','N','N'] (string/char array) --> "Y,N,N" (string)
Hope this helps
Demo

The JavaScript String object has a split method which does what you're requesting. It partitions the string based on a specified delimiter, and returns an array with each partition at its own index. If you split with a blank (empty string) delimiter, you tokenize the string into individual characters.
To get the values of your radio buttons as a string, you can iterate through them and examine the value property of each one.
var input = "YNN"
var result = input.split(''); // returns ["Y", "N", "N"]
var valStr = "";
function main() {
var radioBtns = document.getElementsByName("choice");
for (var i = 0; i < radioBtns.length; i++) {
radioBtns[i].onchange = valChange;
}
valStr = Array(radioBtns.length + 1).join("N")
}
function valChange(event) {
var changedElem = event.target;
var elemValue = changedElem.value;
var elemIdx = +elemValue - 1;
var resultStr = replaceChar(valStr, elemIdx, 'Y');
getElem("outputStr").innerHTML = resultStr;
getElem("outputArr").innerHTML = resultStr.split('');
}
function replaceChar(str, idx, chr) {
return str.substr(0, idx) + chr + str.substr(idx + chr.length);
}
function getElem(id) {
return document.getElementById(id);
}
window.onload = main;
span[id^="output"] {
border: 2px solid black;
margin: 2px;
width: 50px;
}
div {
margin-top: 7px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Select an option:
<br />
<input type="radio" name="choice" value="1" />
<br />
<input type="radio" name="choice" value="2" />
<br />
<input type="radio" name="choice" value="3" />
<div>String Output: <span id="outputStr"> </span>
</div>
<div>Array Output: <span id="outputArr"> </span>
</div>

Related

Javascript loop array for form validation

I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}

Storing multiple values with different id in array - php,javascript

Multiple values are inputted using below code:
$c_num is the count of inputs. There are n number of inputs
$stud['stud_c'] is student codes, S01,S02,S05,S08,S19 .........
On a javascript function calculate(), a portion of id is passed.
code:
<input type="number" required id="c_m_<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>" name="c_m_<?php echo $c_num; ?>[<?php echo $stud['stud_c'];?>]" onkeypress="calculate('<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>','<?php echo $stud['stud_c'];?>')" class="num<?php echo $c_num; ?> " >
When I alert class1, i am getting corresponding output. But how to store multiple values with different id in array? How to store those inputted values in array num[] ? I also want to alert the total of these inputs.
Corresponding script for finding sum of n number of inputs:
function calculate(class1,class2){
var n = parseFloat(document.getElementById('count').value);
var num[] = parseFloat(document.getElementById('c_m_'+class1).value);
var total=0;
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
if (!isNaN(total)) {
document.getElementById('total_mark_'+class2).value = Math.round(total);
}
}
Try like this..
<script>
arr =[];
function calculate(class1)
{
//var n = parseFloat(document.getElementById('count').value);
var num = parseFloat(document.getElementById('c_m_'+class1).value);
arr.push(num);
var total=0;
var n =arr.length;
for (var i = 0; i <n; i++) {
total = total +arr[i];
}
alert(total);
}
</script>
Try this . array.push().And array declaration was wrong.use num=[] instead of num[] .
I don't know why use n on forloop length. if you originaly need the array length use with n=num.length
var num=[];
function calculate(class1)
{
var n = parseFloat(document.getElementById('count').value);
num.push(parseFloat(document.getElementById('c_m_'+class1).value));
var total=0;
//n=num.length if you need num array length use this
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
alert(total);
}
Assign a common attribute for the inputs and fetch them by this attribute. There are many ways to fetch nodes by attribute. To name a few:
parentNode.getElementsByClassName('className') fetches all the child nodes having specific class attribute;
parentNode.querySelectorAll('input[attribute="value"]') fetches a node list of all input tags having specific attribute value
using jQuery selector like 'input[attribute="value"]'
Example
(function() {
var inputs, i, total = 0;
inputs = document.forms.c.querySelectorAll("input[name='c_m[]']");
for (i = 0; i < inputs.length; i++) {
total += Number(inputs[i].value);
}
console.log(total);
})();
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>XXX</title>
</head>
<body>
<form name="c">
<input type="text" name="c_m[]" value="1" size="3" />
<input type="text" name="c_m[]" value="2" size="3" />
<input type="text" name="c_m[]" value="3" size="3" />
</form>
</body>
</html>
Note, you don't need to collect the input values into num array, if you only want to compute the sum of the values. Simply literate the nodes and collect their values. If for some reason you still want to collect the values into an array, use Array.prototype.push method:
var num = [];
for (i = 0; i < inputs.length; i++) {
num.push(inputs[i].value);
}
<script type="text/javascript">
var RECALCULATE = function(a,b) {
var rowtotal = 0;
n = new Array();
var count = document.getElementById('criteria_count').value;
for (i = 1; i <=count; i++) {
if (parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value) > 0) {
n[i] = parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value);
rowtotal += n[i];
}
}
document.getElementById('total_mark_'+b).value = rowtotal;
};
</script>

How to make a list randomizer

I have been working on a fairly pointless website where there are multiple "random" generators. You can check it out here: randomwordgen.net16.net
As you can see there is an unfinished generator at the bottom, that's what I'm here for. I want to get it to generate a list from things you input. My idea is to add the input field's value to the array that will make the list when you hit "Add to List." Then I will have a separate button that will generate the list using that array. The only problem is that I don't know how to add the string to the array when I only know the name of the variable, not the value. If anyone could help me with any of this, that would be great!
This is the code for the whole site:
<!DocType html>
<html>
<head>
<link rel="shortcut icon" href="https://cdn2.iconfinder.com/data/icons/thesquid-ink-40-free-flat-icon-pack/64/rubber-duck-512.png" type="image/x-icon">
<title>Random Word Generator</title>
<style>
body {
background-color:pink;
}
button.10letter {
background-color: blue;
}
button.5letter {
background-color: blue;
position:relative;
top:50px;
}
button.4letter {
background-color: blue;
position:relative;
top:100px;
}
button.3letter {
background-color: blue;
position:relative;
top:150px;
}
button.Add {
position:relative;
top:50px;
}
</style>
</head>
<body>
<h1 style="color:grey">Random word generator:</h1>
<button class="10letter" onclick="doAlert();" style="color:orange">Generate with 10 letters.</button>
<script>
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert() {
alert( "Your word is: "+createRandomWord(10)+" (bonus points if your word is real)." );
}
</script>
<button class="5letter" onclick="doAlert5();" style="color:orange">Generate with 5 letters.</button>
<script>
function createRandomWord5(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert5() {
alert( "Your word is: "+createRandomWord(5)+" (bonus points if your word is real)." );
}
</script>
<button class="4letter" onclick="doAlert4();" style="color:orange">Generate with 4 letters.</button>
<script>
function createRandomWord4(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz♀☺☻ƒ=ù"?',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert4() {
alert( "Your word is: "+createRandomWord(4)+" (bonus points if your word is real)." );
}
</script>
<button class="3letter" onclick="doAlert3();" style="color:orange">Generate with 3 letters.</button>
<script>
function createRandomWord3(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert3() {
alert( "Your word is: "+createRandomWord(3)+" (bonus points if your word is real)." );
}
</script>
<h1 style="color:grey">Name Generator:</h1>
<button style="color:orange" onclick="generator();">Generate</button>
<script>
function generator(){
var first = ["Kick","Stupid","Random Name","Officer","School-Related","Unoriginal","Original","Mousey","Website to name things?","n00b","Error","var first=name.first","Bob","Joe","Boris","Duck","Cheese","Pablo","Stimuli","Last Test Grade","First Word","Puss","Cat","Cherokee", "Jerry", "[Insert Weird First Name Here]"]
var last = ["Me","Idiot","dummy.dummy","randomwordgen.net16.net (shameless advertising)","he went that way","it was him!","DESTRUCTION...","Rats","You need advice for a name, use a website or something! Oh wait.","Opposition","Apple","404 not found","var last=name.last","You sure you want to pick this name?","McGuire","Rox","Knox","Bobert","Green","Raul","Damend","Milk","Positive","Negative","Rocky","Boots","Cherry","Parakeet","[Insert Weird Last Name Here]"]
var randomNumber1 = parseInt(Math.random() * first.length);
var randomNumber2 = parseInt(Math.random() * last.length);
var name = first[randomNumber1] + " " + last[randomNumber2];
alert(name);
}
</script>
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
</body>
</html>
And this is the code for the list part:
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
Thanks in advance!
Here is an example in which we take the input value, add it to an array, shuffle the array and then put it in a list <ul>. Every added value is added to the array and re-shuffles the list.
Try this:
EDIT
I added the shuffle function for when you just want to shuffle without adding new values.
var randomList = [];
function appendToArray() {
var word = document.getElementById("Words").value;
randomList.push(word);
updateList(randomList);
document.getElementById("Words").value = "";
}
function updateList(wordsArr) {
shuffleArr(wordsArr);
var list = document.getElementById('list');
list.innerHTML = "";
for (var i =0; i < wordsArr.length; i++) {
var word = wordsArr[i];
var li = document.createElement('li');
li.innerText = word;
list.appendChild(li);
}
}
function shuffleArr(arr) {
var j,
x,
i;
for (var i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
x = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = x;
}
}
function shuffleList() {
var list = randomList;
updateList(list);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Shuffle" onClick="shuffleList()">Shuffle List</button>
<h3>List</h3>
<ul id="list"></ul>
You will need to make your array variable global so you can access it from multiple functions:
// declare this only once
var arr = [];
function appendToArray() {
var word = document.getElementById("Words").value;
// check to make sure something was entered
if (word && word.length) {
arr.push(word);
// clear the input box if added to the array
document.getElementById("Words").value = '';
}
}
Then you can have another function that picks whatever you need out of the array, which is now accessible because we moved it to the global scope of your document. You could have another button to empty the array then as well.
Is this what are you looking for?
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
function showArray() {
console.log(arr);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Add" onClick="showArray()">Show List</button>
</div>
Initialize array outside the function. Otherwise you are making it empty every time you call the function.
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
</script>
</div>

Push value to array onclick and loop to add array values. Javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

Opening input when writing #Q# in textarea

I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/

Categories

Resources