Get Data in all Fields [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please help me in this issue
I want to fill all the fields with random data
https://jsfiddle.net/omrmstg7/
<html>
<head>
<script>
//<![CDATA[
window.onload=function(){
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
}//]]>
</script>
</head>
<body>
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
<input type="text" id="my-input" />
<input type="text" id="my-input" />
</body>
</html>

I'm guessing your problem is that you want to fill all the inputs and it doesn't do that.
The problem is that id is reserved for unique elements.
So, if you change your HTML for id to be class instead, you would change your JavaScript to something like this:
var button = document.getElementById("my-button");
var inputs = document.getElementsByClassName("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
Array.prototype.forEach.call(inputs, function (input) {
input.value = names[Math.floor(Math.random() * names.length)];
});
});

Change the inputs to use a class instead of an id.
id values should be unique in HTML and getElementById only returns the first matching id.

Related

Why does it come up with 'null' on my website when I try to print a user inputted word later on in the script? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Here's my html so far:
<html>
<body>
<head>
<script>
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
var sentances = ['This new amazing product will be in every home by 2021','Buy this now- before we run out of stock!','Get this now, before everyone else will have one!'].sample()
var quotes = ['“This is amazing!"','"Buy it Now!"'].sample()
var titleback = ['"Nothing can beat','"How can you not love'].sample()
var title = document.getElementById("title")
function myfunction() {
document.getElementById("Sentances").innerHTML = sentances;
document.getElementById("Quotes").innerHTML = quotes;
document.getElementById("Titleback").innerHTML = titleback + title;
}
</script>
</head>
<h2>Auto Ad Generator</h2>
<p>Enter the title of your product:</p>
<form method="post" action=".">
<p><input name="name" id="title"></p>
<button type="button" id="button" onclick="myfunction()">Try it</button>
<p><input name="name2" type="reset"></p>
</form>
<p id="Sentances"></p>
<p id="Sentances2"></p>
<p id="Quotes"></p>
<p id="Titleback"></p>
</body>
</html>
Though when I run this on the website (sites.google.com/view/generator-ad/home), it just prints the word 'null' next to the sentence randomly chosen from 'titleback'. Why does it do this, and not print the name of the product the user inputted at the start? I'm new to javascript and so sorry if the answer is obvious. Any help would be appreciated.
title is a reference to an element. You can't output this to the page.
Instead you presumably want its .value property, to retrieve the value entered by the user.
document.getElementById("Titleback").innerHTML = titleback + title.value;
HtmlInputElement means in this case that you are trying to print out the whole element, instead of the value.
I guess the following example can you help to solve your issue:
Array.prototype.sample = function() { return this[Math.floor(Math.random()*this.length)] };
const submitButton = document.getElementById('submit');
const titleInput = document.getElementById('title');
submitButton.addEventListener('click', e => {
const titleFromArray = ['"Nothing can beat','"How can you not love'].sample();
document.getElementById("Titleback").innerHTML = `${titleFromArray} ${titleInput.value}"`;
});
<input id="title" name="name">
<p id="Titleback"></p>
<button id="submit">Submit</button>
+1 suggestion:
Usually I like better naming convention. For example in this case when you use getElementById then I would suggest to use the variable name with the element type as well. Maybe this is just my personal preference. By doing this you will be sure that you are not mixing up values with DOM elements' references. For example in button case a better name can be just like submitButton. Other example:
const titleInput = document.getElementById('titleInput');
const title = titleInput.value;
I hope this helps!

html form search in Array of objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to be able to search in an array of objects.
I have a HTML-for:
<form action="#" id="filters">
<label for="search">Search</label>
<input type="search" name="search" id="search"/>
</form>
<div id="searchresult"></div>
I have no idea how to begin, can someone help me?
Thanks in advance!
There are more than one ways to achieve what you are trying to do.
One way would be to attach an input event to the input field so that whenever there's a change in the input field value, you can get the input field value and then use filter method to filter the meals array based on the value of the input field. Finally, you can display the filtered results in the searchresult div.
const meals = [
{
id: 1,
title: 'Strawberry Salad with Poppy Seed Dressing',
img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
book: 1
},
{
id: 2,
title: 'Cashew Turkey Salad Sandwiches',
img: 'turkey-sandwich.jpg',
book: 2
}
];
const searchField = document.querySelector('#search');
const searchResultsContainer = document.querySelector('#searchresult');
searchField.addEventListener('input', (e) => {
// if input field is empty, clear the search results
if(e.target.value === '') {
searchResultsContainer.innerHTML = '';
return;
}
// filter the meals array
const searchResults = meals.filter(meal => {
return meal.title.toLowerCase().includes(e.target.value.toLowerCase());
});
// before displaying the search results, clear the search results div
searchResultsContainer.innerHTML = '';
// display the titles of the meal objects that include the text entered in input field
searchResults.forEach((element, index) => {
const p = document.createElement('p');
p.textContent = (index + 1) + '. ' + element.title;
searchResultsContainer.appendChild(p);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form action="#" id="filters">
<label for="search">Search</label>
<input type="search" name="search" id="search"/>
</form>
<div id="searchresult"></div>
</body>
</html>
Without revealing complete code and say, here you are, I will try to navigate you so you can come up with your own solution instead. follow roughly these steps:
listen to your search input = When you type on keyboard you want to
update search results. You can listen for onkeypress,
onkeydown or simple input change
other events inside the input
when key is pressed you need to check the new value inside input = You can do that by checking it's value property.
lastly, you want to get only objects from the list conforming to the
search value = there are sleek JS functions to filter out items in an
array or you can do it in standard for loop
Hope that gives you some idea about what to do. This might be a source of inspiration for you
Try using
array.filter(function(currentValue, index, arr), thisValue)

Storing user inputs (Q & A ) in an array and retrieve the answer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm a beginner in JavaScript & in this task I have I have to do the following;
allow the user to enter questions and answer pairs in an html page which will be stored in an array.
retrieve the answer when one of the questions from the array is asked (different boxes, labels)
Reset the boxes when I press a button
So far, I just know how to store the user input in one single array, append it when a button is pressed and display it.
How do I have two different objects (Question & answer) in the same array that will be an input by the user in pairs and retrieve only the answer when the Question is input again? It kind of works like a Manual Bot.
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for (i = 0; i < myArr.length; i++) {
pval = pval + myArr[i] + "<br/>";
}
// display array data
document.getElementById('pText').innerHTML = pval;
}
<!DOCTYPE html>
<html>
<head>
<title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="text" id="inputText" />
<button onclick="pushData();">Show</button>
<p id="pText"></p>
</body>
</html>
Why not use an object? That way, you can store the Question/Answer pairs with the Question as the key and the answer as its value. Try this out:
var myObj = {};
function pushData() {
// get value from the input text
var question = document.getElementById('inputQuestion').value;
var answer = document.getElementById('inputAnswer').value;
// add data to the object
myObj[question] = answer;
}
function getAnswer() {
var question = document.getElementById('inputRetrieveQuestion').value;
if (myObj[question]) {
document.getElementById('pText').innerHTML = myObj[question];
}
}
<html>
<body>
<h3> Enter a Question/Answer </h3>
Question <input type="text" name="question" id="inputQuestion" /> Answer <input type="text" name="answer" id="inputAnswer" />
<button onclick="pushData()">Submit</button>
</br>
<h3> Retrieve an Answer </h3>
Question <input type="text" name="question" id="inputRetrieveQuestion" />
<button onclick="getAnswer()">Submit</button>
</br>
Answer:
<div id="pText"></div>
</body>
</html>

which takes the text thats is input in the inputbox in html and display it below as a clickable option. [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a project, which takes the text that is input in the inputbox and display it below as a clickable option/button in html. Is it possible to make such thing, if yes please let me know, any help would be highly appreciated.
If you want in javascript :
<input type="text" id="fname" onkeyup="myFunction()">
<button id='button' style='display:none;'></button>
<script>
function myFunction() {
var x = document.getElementById("fname");
document.getElementById("button").innerHTML = x.value
var x = document.getElementById('button');
if (x.style.display === 'none') {
x.style.display = 'block';
}
}
</script>
We have 2 elements one is input on which providing any input will appear on the next hidden element (button) document.getElementById("fname") will find the element and next line is changing the value of button and then we are making button appear which is hidden till now.
We can also do the very similar thing using jquery
<input type="text" id="fname">
<button id='button' style='display:none;'></button>
$( "#fname" ).keyup(function() {
$("#button").show();
$("#button").html($(this).val());
})
Is this what are youre looking for?
function add() {
var option = document.createElement("option");
option.text = document.getElementById("toadd").value;
document.getElementById("option").add(option);
}
function add2() {
var aTag = document.createElement("button");
aTag.setAttribute ("id", Date.now())
aTag.innerHTML = document.getElementById("toadd").value;;
document.getElementById("thisdiv").appendChild(aTag);
}
<input id="toadd" type="text"/>
<button onClick="add()" >Add</button>
<button onClick="add2()" >Add in another way</button>
<select id="option">
</select>
<div id="thisdiv"></div>

Jquery selector for all elements with class in a form that are after one element [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need to find all elements with class 'complexList' in form that are after 'el'.
Example
var el = $(this);
var els = $('#' + obj.tableId + '_editorForm').find('.complexList');
el.nextAll('.complexList') //dont work
Thanks
If nextAll doesn't work, it means there are elements at various levels of nesting. But you can still do it, with index and slice.
els = els.slice(els.index(el) + 1);
index, when called as above, finds the index of the given element in the matched set; slice returns a subset of elements from a set. So we ask for the subset starting with the element after el.
Example:
var obj = {
tableId: "foo"
};
$(document.body).on("click", ".complexList", function() {
var el = $(this);
var els = $('#' + obj.tableId + '_editorForm').find('.complexList');
els.css("color", ""); // clear previous
els = els.slice(els.index(el) + 1);
els.css("color", "blue");
});
All of the text fields below are `.complexList` fields. Click any of them to turn all `.complexList` elements <em>after</em> it blue.
<form id="foo_editorForm">
<label>
Field 1:
<input type="text" class="complexList" value="field1">
</label>
<label>
Field 2:
<input type="text" class="complexList" value="field2">
</label>
<label>
Field 3:
<input type="text" class="complexList" value="field3">
</label>
<label>
Field 4:
<input type="text" class="complexList" value="field4">
</label>
<label>
Field 5:
<input type="text" class="complexList" value="field4">
</label>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories