I am trying to display multiple user outputs, so that when something is entered in the text field, it is captured and displayed in the div.
At the moment it keeps overwriting with the new result rather than adding to what is already displayed.
Can anyone help with this?
HTML:
<!DOCTYPE HTML>
<html lang="en">
<!-- more meta data needs to go in here -->
<head>
<script type="text/javascript" src="main_app_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="">
<meta charset="UTF-8">
<title>List Check</title>
</head>
<body>
<input type="text" id="enter_box">
<button onclick="output_function()"> Add To List </button>
<div id="list_output"></div>
</body>
JavaScript:
function output_function() {
var user_input = document.getElementById("enter_box").value;
document.getElementById("list_output").innerHTML = user_input;
}
Do
document.getElementById("list_output").innerHTML += user_input + '<br />';
instead.
This will concatenate your value and add a line break at the end of the text, to create a "list". Notice the =+ and + '<br /> differences.
You could also try this
function output_function() {
'use strict';
var user_input = document.getElementById("enter_box").value;
var list_output = document.getElementById("list_output");
if( list_output.innerHTML === '' ) {
list_output.innerHTML = '<p>' + user_input + '</p>';
} else {
list_output.innerHTML += '<p>' + user_input + '</p>';
}
}
Related
In my palindrome checker, i can't obtain value from the HTML input text-field. I tried various methods including query-selectors. But nonetheless is working. Error in the validator is document.getElement(...) is null.
i need to find whats wrong with my code. Is there any problem in my DOM?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i = document.getElementById('boiler').value;
function check_pal() {
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
I am little sure that my problem is with document model. Because i get correct result when i directly assign the value to the variable. Or else i get "undefined is not a palindrome"
Update your script to following
<script>
function check_pal() {
// move this line inside the function
var i = document.getElementById('boiler').value;
// rev(); // Also removed this un-necessary call
if (i == rev(i)) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
// modify function to take input as argument rather than relying on global variable
function rev(i) {
i = i + "";
return i.split("").reverse().join("");
}
</script>
Reasoning - When you manually assigned the value of i, then it was running correctly. However, when were trying to read it from the getElementById, the element did not existed by then and it throws a JS error (cannot read property 'value' of null), hence, the error (as i was never initialized and remains undefined). Move the retrieving of value inside the function where the latest value can be retrieved and stored in i.
This should solve it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i;
function check_pal() {
i = document.getElementById('boiler').value;
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
Now the i variable gets assigned in the check_pal function and declared in the global space so both functions can access it. I think you should take a close look in scope in javascript.
I Have A function that add html to a div.
var user = $("#ddlUser").val();
var role = $("#ddlUserRole").val();
var html = '<div class="calendaruser">';
html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
html += '<div>' + role + '</div>';
html += '</div>';
$("#divCalendarUsers").append(html);
i'm looking for a better way to use the template.
You can use the template literal:
A little sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Array2Table</title>
</head>
<body>
<div id="tableContent"></div>
<script>
var country = ["Country1", "Country2", "Country3"];
var capital = ["City1", "City2" , "City3"];
const tmpl = (country,capital) => `
<table><thead>
<tr><th>Country<th>Capital<tbody>
${country.map( (cell, index) => `
<tr><td>${cell}<td>${capital[index]}</tr>
`).join('')}
</table>`;
tableContent.innerHTML=tmpl(country, capital);
</script>
</body>
</html>
To use template in javascript, try handlebarsjs.
I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want
function createTemplate(user,role){
var divCalendar=$('<div class="calendaruser"></div>');
var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
var spanElm=$('<span>'+user+'</span>');
var divELm=$('<div>'+role+'</div>');
divCalendar.append(buttonElm).append(spanElm).append(divELm);
return divCalendar;
}
//Example below:
$('body').append(createTemplate('user_value', 'role_value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I have an array in my script.js file. The array contains around 12 different things. I use the array to store divs IDs'. Because I want to load those divs dynamically. I've done that I loaded the divs dynamically but now I want to use that array for loading things inside the first div(a title a picture and so on).
let donorFeatureNames = [
'SpawnVehicle',
'RepairVehicle',
'RocketVoltic',
'MoreVehicle',
'ChatColors',
'Deagle',
'M4',
'Sniper',
'CopFeature',
'CrimFeature',
'Changeskin',
'Cash'
]
function loadFeatures () {
for (i = 0; i < 12; i++) {
$('#featureMenu').append('<div id=' + '"' + donorFeatureNames[i] + '"' + 'class="item notLoaded"></div>')
$("'#" + donorFeatureNames[i] + "'").append(span class="title">' + $(this).data('donorfeature') + '</span>)
}
I hope you understand what I'm asking. Cause I'm not that good at explaining things.
Instead of an array, just use jquery:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index1001</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
//credit to https://stackoverflow.com/questions/941206/jquery-add-image-inside-of-div-tag
$(function () {
$("#test1").append("Text");
$('#test2').prepend("<img src='../../Images/w.JPG' />")
})
</script>
</head>
<body>
<div id="test1" class="anArray"></div>
<br/>
<div id="test2" class="anArray"></div>
</body>
</html>
You can even do this to make an array: $(".anArray").addClass("aColor");
Huangism answered my question.
$("'#" + donorFeatureNames[i] + "'") isn't correct, but this is: $("#" + donorFeatureNames[i])
That's basically what I asked.
Thanks a lot man!
How should I read values from iframe1 and send it to iframe2 as HTML? Either JavaScript or jQuery is acceptable - it does not matter. I'm new to javascript. I already found code like the one below, maybe this will help.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getIframeText() {
var iframe0 = document.getElementById("iframe0");
var iframe0document=iframe0.contentDocument||iframe0.contentWindow.document;
var inputIframe = iframe0document.getElementById("frame_text");
alert(inputIframe.value);
}
</script>
</head>
<body>
<div>
<button onclick="getIframeText()">get iframe text</button>
<iframe id="iframe0" src="test.html" >
<input type=text id="parent_text">
</div>
</body>
</html>
Take a look to this: http://jsfiddle.net/nick_craver/c5JeU/2/
$('button').click(function(){
var fjq = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');
f.append( '----------<br>');
f.append( 'test1: ' + fjq.data(f[0], 'test1') + '<br>test2: ' + fjq.data(f[0], 'test2') + '<br>' );
f.append( 'test3: ' + typeof (fjq.data(f[0], 'test3')) + '<br>' );
})
I found it on: Access jQuery data from iframe element
I am learning JS and I am not yet familiar with internal workings. Can someone point out the error in my thinking?
The basic idea is to ask a complex question, construct the answer with JS (to a CSV syntax) and feed it to a textbox. (From here it will be processed to a db.) Example included below: How many children do you have? What is their names and age?
Perhaps, the new element generated by the first button is not added to the document? How to do this, or how to address the value in it?
How can I make the values submitted to previous lines stick in the event of adding a new line. For example 'Jack' and '10' is written to the first line, the user pressed the add new line, than this information should stay in the first line.
Incorrectly working example: The save button stops working if the code in the loop is added.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines = 0;
function addNew() {
lines++;
document.getElementById("qchildren-answer-wrapper").innerHTML += 'Gyermek neve:<input type="text" id="qchildrenname' + window.lines + '" /> Gyermek eletkora:<input type="text" id="qchildrenage' + window.lines + '" /><br/>';
}
function save() {
var answer = '';
for (var ii = 0; ii < window.lines; ii++) {
answer += document.getElementById('qchildrenname' + ii.toString()).value.toString() + ',' + document.getElementById('qchildrenage' + ii.toString()).value.toString() + ';';
}
document.getElementById("qchildren").value = answer;
}
< /script>
</body>
</html>
=Below code should work (AddNew function changed):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
newElement.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}
function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
document.getElementById("qchildren").value=answer;
}
</script>
</body>
</html>
Try code like this:
function addNew()
{
var div = document.createElement('div');
div.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(div );
lines++;
}
Demo: http://jsfiddle.net/JByVg/8/
What happens in your case is that all previously created elements are recreated again because element.innerHTML += "some_html" is equal to element.innerHTML = element.innerHTML + "some_html" or, more clear, I suppose, var oldHtml = element.innerHTML;element.innerHTML = ""; element.innerHTML = oldHtml + "some_html"
Browser does not populate value="..." entered by user when you do var oldHtml = element.innerHTML and after += you have old elements recreated without values entered by user. At the same time, appendChild does not recreate old elements.
This example demonstrates how .innerHTML returns only initial HTML (I've added value="test" to your qchildrenname element code)