I dont know if its a browser bug or something else, because I have tested on Chrome and Firefox. I get same result. I tried to input value element only 1,10,100 that identified. This's my code.
HTML
<input id="items" type="text" placeholder="title" value="">
<input id="start" type="text" placeholder="start" value="">
<input id="end" type="text" placeholder="end" value="">
<input id="btn" type="submit" value="Generate"><br><br>
<div id="output" contenteditable="true"></div>
JavaScript
<script>
var btn = document.getElementById('btn')
var output = document.getElementById('output');
btn.addEventListener('click', function(){
var items = document.getElementById('items').value;
var i = document.getElementById('start').value;
var e = document.getElementById('end').value;
for(i; i<=e; i++){
output.innerHTML += items+'/'+i;
}
}, false);
</script>
It would not generate if start value input element is not 1,10,100. How can I make it to work? Start from 2,3,4,5,6,7,8,9?
You need to convert your values to Integers:
var i = parseInt( document.getElementById('start').value, 10 );
var e = parseInt( document.getElementById('end').value, 10 );
Related
There is a list of rules. The rules specify how to change the word entered. The screenshot shows an example of how the program should work. The result should be a string "aBct". I don't understand how to do this.
function pushRules(list){
var rules = "";
var w1 = document.getElementById('inputw1').value;
var w2 = document.getElementById('inputw2').value;
var w = w1+'-->'+w2;
var li = document.createElement("li");
var rule = document.createTextNode(w);
li.appendChild(rule);
}
function applyRule() {
var str = document.getElementById('inputString').value;
var numRule = document.getElementById('inputNumRules').value;
for(var i=0; i<str.length; i++){
// ...
}
}
<div class="addRules">
<h3>Add Rules</h3>
<form>
<label>w1:</label><input id="inputw1" type="text"><label> --> w2:</label><input id="inputw2" type="text">
<input type="button" value="Add" onclick="pushRules()">
</form>
<h3>Rules:</h3>
<div class="container_rules">
<ui id="list"></ui>
</div>
</div>
<h3>Input string</h3>
<input type="text" id="inputString">
<form>
<p>Apply the selected rule to the symbol at number:</p><input type="text" id="inputNumRules" value="0">
<input type="button" value="Apply rule" onclick="applyRule()">
</form>
<h3>Result</h3>
Working solution.
Just insert rules and then write the number of rule you want to apply starting from 0
var changeStringFromRules = [];
var changeStringToRules = [];
function pushRules(list){
var rules = "";
var w1 = document.getElementById('inputw1').value;
changeStringFromRules.push(w1);
var w2 = document.getElementById('inputw2').value;
changeStringToRules.push(w2);
var w = w1+'-->'+w2;
var li = document.createElement("li");
var rule = document.createTextNode(w);
li.appendChild(rule);
document.getElementById("list").appendChild(li);
}
function applyRule() {
var str = document.getElementById('inputString').value;
var numRule = parseInt(document.getElementById('inputNumRules').value);
if(str.indexOf(changeStringFromRules[numRule])!== -1){
str = str.replace(changeStringFromRules[numRule], changeStringToRules[numRule]);
}
document.getElementById("result").innerHTML = str;
}
<div class="addRules">
<h3>Add Rules</h3>
<form>
<label>w1:</label><input id="inputw1" type="text"><label> --> w2:</label><input id="inputw2" type="text">
<input type="button" value="Add" onclick="pushRules()">
</form>
<h3>Rules:</h3>
<div class="container_rules">
<ui id="list"></ui>
</div>
</div>
<h3>Input string</h3>
<input type="text" id="inputString">
<form>
<p>Apply the selected rule to the symbol at number:</p><input type="text" id="inputNumRules" value="0">
<input type="button" value="Apply rule" onclick="applyRule()">
</form>
<h3>Result</h3>
<p id="result"></p>
If I understood the question correctly, You just have to replace few characters in the input string with other characters.
You can use replace() method.
So all you have to do is,
"aBcah".replace(/ah/g,'t');
This means, replace all occurrences of ah with t in the string aBcah.
I have used a regex here and /g means to remove all(global flag), without it, it will only remove the first occurrence.
var a = "aBcah".replace(/ah/g,'t');
console.log(a);
Normally if I add a new input tag I also have to add in Javascript.
I try to collect all value from input tag,
So how to pass value into an object by loop
use tag input name to be object key name also.
Try to use for count
document.getElementById("form1").elements.length
seem it collected the button tag also, how to void it
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" onClick="fc1()" value="Save">
</form>
for(i=0;......)
{
obj.value+'i' = document.forms["form1"]["value"+ (i+1)].value;
}
Same result as this.
function fc1(){
this.value1 = document.forms["form1"]["value1"].value;
this.value2 = document.forms["form1"]["value2"].value;
this.value3 = document.forms["form1"]["value3"].value;
this.value4 = document.forms["form1"]["value4"].value;
const obj = {
"value1": this.value1,
"value2": this.value2,
"value3": this.value3,
"value4": this.value4
};
}
I usually grab inputs by their ID or class:
<input type="text" id="value1">
then grab the value:
const value1 = document.getElementById('value1').value
to cut down on code, maybe throw it in an array:
const valueArray = [value1, value2, value3]
then you can do something like this:
const allValues = {}
valueArray.forEach((value, index) => {
allValues[`value${index + 1}`] = value
})
now when you log allValues you should have what you want. Note, I am using some es6.
What about this ?
var obj = {};
var form = document.getElementById("form1");
form.children.forEach(function(elm){
if(elm.type === 'text'){
obj[elm.name] = elm.value;
}
});
console.log(obj);
try giving same 'class' or 'name' attribute to the text fields.
try var x = document.getElementsByClassName("example");
which gives you the list of all elements with the class name as "example'. Then you can loop around based on the length of x.
References:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try this:
var input = document.forms[0].querySelectorAll('input[type=text]');
var result = Array.from(input).reduce((r, ele) => {
r[ele.name] = ele.value;
return r;
}, {});
console.log(result);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
If you used something like .. I think it will work. :)
var myObj = {};
var elems = document.getElementsByTagName('input'), i;
for (i in elems) {
myObj[value + i] = myObj[i].value;
}
return from getElementsByTagName is an array of all matching tags. there are some wizard answers in here ha. :)
document.querySelectorAll is made for this.
document.querySelectorAll("form[name='form1'] input[type='text']")
will return all input fields of type text in form1 as HTML nodes.
let elements = document.querySelectorAll("form[name='form1'] input[type='text']");
elements.forEach(e => console.log(e.value));
...logs the values of the input fields. Don't make things harder on yourself by hard coding classes or ID's, and this will allow you to target the input elements you need without additional checks or without fetching every input on the page.
Example:
const values = {};
document.querySelectorAll("form[name='form1'] input[type='text']").forEach(element => values[element.name] = element.value);
console.log(values);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
This is an alternative solution done with jQuery.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
//jQuery solution
const obj = {}
$('#save').click(function(e){
var form = $(this).parent();
var inputs = form.children().not(':input[type=button]');
$.each( inputs, function(){
obj[$(this).attr('name')] = $(this).val();
});
console.log(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>jQuery solution</h2>
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" value="Save">
</form>
JS Solution
//JS Solution
const objs = {}
var button = document.getElementById('savejs');
var form = document.getElementById('formjs');
var element = {};
button.addEventListener('click', function(){
inputs = form.children;
for(i=0; i < inputs.length; i++){
if(inputs[i].name != ""){
objs[inputs[i].name] = inputs[i].value;
}
}
console.log(objs);
})
<h2>JS solution</h2>
<form name="form1" id='formjs'>
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="savejs" value="Save">
</form>
I try to pass the textbox value from a page to another page.
I try to pass that text box but failed I use javascript for doing that.
I have to try to change my code properly but still not work
the error is the data that passing to the text box is multiple.
this is my code
1st-page code
function myFunction() {
var inputTest = document.getElementById('tanggal2').value;
var inputTest1 = document.getElementById('dt').value;
localStorage.setItem( 'objectToPass', inputTest );
localStorage.setItem( 'objectToPass1', inputTest1 );
if (inputTest=="") {
window.open('report_pengambilan_singgle.html','','height=650,width=1200');
}
else {
window.open('report_pengambilan_singgle1.html','','height=650,width=1200');
}
}
<input type="text" id="dt" type="text" name="dt" maxlength="1" size="23" readonly="readonly" style="visibility:hidden" />
<input type="text" id="tanggal2" type="text" name="tanggal2" maxlength="1" size="23" readonly="readonly" style="visibility:hidden" />
<label onclick="myFunction();" >a</label>
and this my 2nd-page code
var inputTest = localStorage.getItem('objectToPass');
var inputTest1 = localStorage.getItem('objectToPass1');
var displayData = inputTest;
var displayData = inputTest1;
document.getElementById("datepicker1").value=inputTest;
document.getElementById("datepicker2").value=inputTest;
document.getElementById("datepicker3").value=inputTest;
localStorage.removeItem( 'objectToPass1' ); // Clear the localStorage
localStorage.removeItem( 'objectToPass' ); // Clear the localStorage
Try this way...
test.html
<script>function myFunction() {
var inputTest = document.getElementById('tanggal2').value;
var inputTest1 = document.getElementById('dt').value;
if (inputTest=="") {
window.open('report_pengambilan_singgle.html','','height=650,width=1200');
}
else {
window.open('test1.html?name=' + inputTest1,'','height=650,width=1200');
}
}
</script>
<input type="text" id="dt" type="text" name="dt" size="23" />
<input type="text" id="tanggal2" type="text" name="tanggal2" size="23" />
<button onclick="myFunction();" >a</button>
test1.html
<script>window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById("datepicker1").value = data.name;
}
</script>
<input type="text" id="datepicker1" type="text" name="datepicker1" size="23" />
i Hope working for u...
you have textbox which have hidden and not any value define
so first set any value in textbox and create textbox in another page before your <script> start
like
<input type="text" id="datepicker1" value="">
<input type="text" id="datepicker2" value="">
<input type="text" id="datepicker3" value="">
Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/
Well so far i havent been able to get it to change the input box value.
What i want it to do?
I want it to take the text from the first box. And when you click the button splits it and appends them to the 2nd and 3rd box.
I don't want to use jquery or any libraries purely javascript.
Any questions ask away.
Not sure what im doing wrong here. Seems it should work. Any help? Thanks
Edited this is working for what i need.... not sure if its the best way but it does work
Code
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var urls_1;
var split_text;
function addto_boxes(form) {
var split_text = document.getElementById("text_to_split").value;
var urls_1 = split_text.split(" ", 100000);
document.getElementById("input_box1").value = document.getElementById("input_box1").value + urls_1[0] + " ";
document.getElementById("input_box2").value = document.getElementById("input_box2").value + urls_1[1] + " ";
}
</SCRIPT>
</HEAD>
<BODY>
<input id="Split" type="button" value="Add to boxes" onclick="addto_boxes(this.form);"/><Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea><Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE=""rows="4" cols="75"></textarea><Br>
Put 2nd urls in this box: <Br>
<textarea NAME="inputbox2" id="input_box2" VALUE=""rows="4" cols="75"></textarea><Br>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>
This should work for you
HTML
<input id="Split" type="button" value="Add to boxes" />
<Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea>
<Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE="" rows="4" cols="75"></textarea>
<Br>Put 2nd urls in this box:
<Br>
<textarea NAME="inputbox2" id="input_box2" VALUE="" rows="4" cols="75"></textarea>
<Br>
<INPUT id="reset" TYPE="reset">
</FORM>
Javascript
var aBox1 = [];
var aBox2 = [];
document.getElementById("Split").addEventListener("click", function () {
var urls_1 = document.getElementById("text_to_split").value.trim().split(" "),
url1 = urls_1[0] || "",
url2 = urls_1[1] || "";
if (url1.length) {
aBox1.push(url1);
}
if (url2.length) {
aBox2.push(url2);
}
document.getElementById("input_box1").value = aBox1.join(" ");
document.getElementById("input_box2").value = aBox2.join(" ");
}, false);
document.getElementById("reset").addEventListener("click", function () {
aBox1.length = 0;
aBox2.length = 0;
}, false);
On jsfiddle