Combining two input fields into one variable - javascript

Include two IDs into one variable, for example
var optionValue=document.getElementById('Input1' + " " + 'Input2');
That code does not work but is there any similar code that would do this?
JS
function addNewListItem(){
var htmlSelect=document.getElementById('list');
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var optionDisplaytext = value1 + " " + value2;
var selectBoxOption = document.createElement("option");
selectBoxOption.value = optionValue.value;
selectBoxOption.text = optionDisplaytext.value;
htmlSelect.add(selectBoxOption, null);
alert("Option has been added successfully");
return true;
}
HTML
<table border="0" align="left">
<tr>
<td rowspan="2">
<select name="list" id="list" size="10" style="width:150px">
</select>
</td>
<tr>
<td align="right">Option Value</td>
<td align="left"><input name="Input1" type="text" id="Input1" /></td>
</tr>
<tr>
<td align="right">Option Display Text</td>
<td align="left"><input name="Input2" type="text" id="Input2" /></td>
</tr>
<tr>
<td align="right"> </td>
<td align="left"><input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javaScript:addNewListItem();" /></td>
</tr>
</table>
I've tried the above code but it will not add to a listbox?
it just says undefined in the box

Elements are text inputs ? Then somethink like below will work :
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;

Further to a comment I left, here's a full example.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('mBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick()
{
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var newOpt = newEl('option');
newOpt.value = optionValue; // this line sets the value given to a form by this option
newOpt.appendChild( newTxt(optionValue) ); // this line adds the text viewable on the page
byId('mSelect').appendChild(newOpt);
}
</script>
<style>
</style>
</head>
<body>
<label>Input 1: <input id='Input1' value='value1'/></label>
<label>Input 2: <input id='Input2' value='value2'/></label>
<br>
<select id='mSelect'></select><button id='mBtn'>Add to list</button>
</body>
</html>

I interpreted your question as follows:
Get n-number of elements by id.
You can do this with the following block:
HTML
<span id="foo">Foo</span>
<span id="bar">Bar</span>
<span id="foo1">Foo</span>
<span id="bar1">Bar</span>
JS
var nodes = document.querySelectorAll('#foo, #bar');
console.log(nodes);
You can then derive any data you want from each matched node.

Related

I want to add new data from second table to main table

I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

Automatic start time when a link is clicked [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 5 years ago.
I would like to seek your expertise with regards to the coding below:
this is the layout of my browser, so i divided my page into 2
<FRAMESET rows="5%,*" border=0>
<FRAME SRC="MENU.HTML">
<FRAMESET rows="50%,*">
<FRAME SRC="" NAME=1>
<FRAME SRC="" NAME=2>
</FRAMESET>
</FRAMSET>
below is the code in which i would like to setup the start time automatic where in it will be the same start time in the label.
<html>
<head >
<title>Start and stop</TITLE>
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
<script>function getDateString(){
var myDate = new Date();
return padDatePart(myDate.getMonth() + 1) +
"/" + padDatePart(myDate.getDate()) +
"/" + myDate.getFullYear()+
' ' + padDatePart(myDate.getHours()) +
":" + padDatePart(myDate.getMinutes()) +
":" + padDatePart(myDate.getSeconds());
}
function padDatePart(part){
return ('0'+part).slice(-2);
}
</script>
<script>
function clearFields(formName)
{
var formElements = formName.elements;
for(var i=0;i<formElements.length;i++)
{
var elementType = formElements[i].type;
if('text' == elementType){
formElements[i].value="";
formElements[i].disabled = false;
}
else if('select-one' == elementType){
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
}
else if('select-multiple' == elementType)
{
var multiOptions = formElements[i].options;
for(var j=0;j<multiOptions.length;j++)
{
multiOptions[j].selected = false;
}
}
}
}
</script>
</head>
<form>
<body BGCOLOR=#FFFF99 SCROLL=NO>
<CENTER>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START " >
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled">
| <label id="minutes">00</label>:<label id="seconds">00</label> |
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>
</body>
</html>
</br></br></html>
is it possible to have automatic stop as well when i clicked the stop button?
Move the stuff that needs to be set after the page has rendered to an onload
make sure the table is wrapped in correct form tags
function pad(part) {
return ('0' + part).slice(-2);
}
function getDateString() {
var myDate = new Date();
return pad(myDate.getMonth() + 1) +
"/" + pad(myDate.getDate()) +
"/" + myDate.getFullYear() +
' ' + pad(myDate.getHours()) +
":" + pad(myDate.getMinutes()) +
":" + pad(myDate.getSeconds());
}
function clearFields(formName) {
var formElements = formName.elements;
for (var i = 0; i < formElements.length; i++) {
var elementType = formElements[i].type;
if ('text' == elementType) {
formElements[i].value = "";
formElements[i].disabled = false;
} else if ('select-one' == elementType) {
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
} else if ('select-multiple' == elementType) {
var multiOptions = formElements[i].options;
for (var j = 0; j < multiOptions.length; j++) {
multiOptions[j].selected = false;
}
}
}
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
var minutesLabel, secondsLabel, totalSeconds = 0;
window.onload = function() {
document.getElementById('date').value = Date();
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
setInterval(setTime, 1000);
}
<form>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START ">
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled"> | <label id="minutes">00</label>:<label id="seconds">00</label> |
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>

In the first page i was passing the values in textbox then i should get the data in second page in text box using only Javascript?

In the first page entered the values using text box,In second page also it should display in the text box.But it is not displaying like that.......
Below is my first page pass.html:
<html>
<head>
<script type="text/javascript">function getParams()
{
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx !=-1)
{
var pairs = document.URL.substring(idx+1,
document.URL.length).split('&');
for (var i=0; i<pairs.length; i++)
{
console.log(pairs.length);
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</head>
</html>
And below is my second page pass1.html
<html>
<form type=get action="pass1.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=number name=age></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</html>

Separate check box value to separate text area

<script>
var itemsAdded = Array();
function moveNumbers(text) {
var i = itemsAdded.indexOf(text)
if ( i >= 0) {
itemsAdded.splice(i,1);
} else {
itemsAdded.push(text);
}
document.getElementById("result1").value=itemsAdded.join(" ");
if ( i >= 0) {
} else{
itemsAdded.push(text);
}
document.getElementById("result2").value=itemsAdded.join(" ");
}
$(function() {
for (i=0;i<10;i++) {
console.log(i);
$("body").append("<input type='checkbox' name='add' value='" + i + "'
onclick='moveNumbers(this.value)'/> Checkbox" + i + "<br/>");
}
});
</script>
<table width="95%" height="24" border="1" align="center">
<tr>
<th><h2>Selected Image 5x7</h2></th>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result1" style="background:#B0D2D7;
width:100%;overflow:auto;resize:none"
readonly></textarea>
</td>
</tr>
<tr><tr>
<th><h2>Selected Image 6x8</h2></th>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result2" style="background:#B0D2D7;
width:100%;overflow:auto;resize:none"
readonly></textarea>
</td></tr>
</table>
Hi all, new at this so I apologize if it's rather messy.
I have this working but when I check the boxes the value's do appear in the text areas, but text it self is all over the place. Also need the check boxes, when unchecked to remove the text from the text area. Any ideas would be great! Hopes this makes sense...
Cheers.
It doesn't have to be so messy as you describe. Besides, I don't know how it is working for you as the structure of html is clearly broken in the current state.
Following is a bit of updated code, which I believe is equivalent to what you are trying to achieve with your snippet. DEMO
JS:
var itemsAdded = Array();
function moveNumbers() {
var text = this.value;
var i = itemsAdded.indexOf(text)
if (i >= 0) itemsAdded.splice(i, 1);
else itemsAdded.push(text);
document.getElementById("result1").value = itemsAdded.join(" ");
if (i < 0) itemsAdded.push(text);
document.getElementById("result2").value = itemsAdded.join(" ");
}
$(function () {
for (i = 0; i < 10; i++)
$("<div>Checkbox" + i + "</div>").appendTo(document.body)
.prepend($("<input type='checkbox' name='add'/>")
.val(i).click(moveNumbers));
});
HTML:
<table width="95%" height="24" border="1" align="center">
<tr>
<th>
<h2>Selected Image 5x7</h2>
</th>
</tr>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result1" readonly></textarea>
</td>
</tr>
<tr>
<th>
<h2>Selected Image 6x8</h2>
</th>
</tr>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result2" readonly></textarea>
</td>
</tr>
</table>
CSS:
textarea {
background:#B0D2D7;
width:100%;
overflow:auto;
resize:none
}
Try this http://jsfiddle.net/KCmbm/2/
NOTE: if you are not going to use special tags like [b]: use commented code(but it will replace all occurences of supplied text);
Javscript
var itemsAdded = Array();
function moveNumbers(text) {
console.log(text);
var addedText = '[b' + text + ']' + text + '[/b]';
$('#result1').val($('#result1').val() + addedText);
//$('#result1').val($('#result1').val() + text);
console.log(addedText);
}
function removeText(text){
//$('#result1').val($('#result1').val().replace(new RegExp(text, 'g'), ''));
$('#result1').val($('#result1').val().replace('[b' + text + ']' + text + '[/b]', ''));
}
$(document).ready(function(){
$('.chkAdd').on('change', function(){
$(this).prop('checked') ? moveNumbers($(this).val()) : removeText($(this).val());
});
})
You are not attaching the on click event correctly. They don't even get fired. See this example below. Once the checkboxes are added, attach the click event. You can get the value of the element from this as shown below. JS fiddle
var itemsAdded = Array();
function moveNumbers() {
var i = itemsAdded.indexOf(this.value)
if (i >= 0) {
itemsAdded.splice(i, 1);
} else {
itemsAdded.push(this.value);
}
document.getElementById("result1").value = itemsAdded.join(" ");
if (i < 0) {
itemsAdded.push(this.value);
}
document.getElementById("result2").value = itemsAdded.join(" ");
}
$(function () {
for (i = 0; i < 10; i++) {
console.log(i);
$("body").append("<input type='checkbox' name='add' value='" + i + "'/> Checkbox" + i + "<br/>");
}
$("input:checkbox").click(moveNumbers);
});

Categories

Resources