Nothing appears on console in chrome,taking information from form - javascript

I'm creating a simple string reverse project.
I want the user to enter input, then that input will be displayed below the text box in reverse order.
<form id = "frm1">
<input type="text" id="userInput"=> give me input</input>
<button onclick="strRev()">Submit</button>
</form>
<script type="text/javascript">
function strRev(str){
str = document.getElementById("userInput").toString().value;
console.log(str);
var originalStr = str.split("");
console.log(originalStr);
var finalArray = [];
var j = 0;
for(i = originalStr.length-1; i >= 0; i--){
finalArray[j] = originalStr[i];
j++;
}
for(k = 0; k <finalArray.length; k++){
document.write(finalArray[k]);
}
}
</script>
When pressing submit, the information in the box is what should be reversed
Nothing happens on submit and nothing appears in console to debug.

Try the below code:
str = document.getElementById("userInput").value;

onclick="strRev()"
and you are calling
function strRev(str) // function with one argument, must be showing error in console

Add type="button" in your button input, that way the form won't refresh
<button type=button onclick="strRev()">Submit</button>
You will probably be able to continue solving your other problems after that.

You have an error in your html here <input type="text" id="userInput"=>
it should be <input type="text" id="userInput">
also fetching the value of input should be like this
str = document.getElementById("userInput").value;
After applying these changes you will see the output in console

Related

Using user input for javascript function (for loop)

I have a basic js function that connects to my html file. I want the user to input a number and then the function will count up to that number. As it counts it will display a circle with each number. So, input 3 and you'll see three circles counting 1, 2, 3 horizontally on the page.
When I call the function and hard code an input like:
display(9)
it works fine.
I console log my user input, I console log as I loop through and it's counting just fine, but for some reason,
const button = document.getElementById("button");
const main = document.querySelector("main");
let number = "";
function display(num) {
for (let i = 1; i <= num; i++) {
console.log("in the loop " + i);
number += `<div>${i}</div>`;
}
}
button.addEventListener('click', () => {
let input = parseInt(document.getElementById("input").value);
console.log(input);
display(input);
});
document.getElementById("display").innerHTML = number;
<h1 class="h1">Test Form</h1>
<input class="input" id="input" type="text" />
<input type="button" id="button" value="Enter" />
<p class="display" id="display"></p>
it won't display anything using user input.
My code is below. Thoughts? And thank you for the help!
You just add the following statements to the end of display function to make it work.
let displayDiv=document.getElementByI("display");
displayDiv.innerHTML=number;

how to update value in textarea after clicking a button?

I'm practicing JavaScript creating a convert case where I have a textarea where the initial text is informed and the second where the converted result should be output, I created a function to invert the text but when I click on the button that calls this function it doesn't convert if there is already a typed text.
How do I get it to update the values ​​when I click on the button?
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>
I want to create other conversion functions so I want the value the user has already typed to be converted as soon as he clicks on one of the conversion options.
If I understand your question you want the button to directly convert the text. Right now you code is doing the reverse, but update the input only after user type a key.
You want to revert instantly on button click, and keep the update going
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
function updateInput() {
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
}
$('#input1').keyup(updateInput);
updateInput();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>
I don't really get what you want. If you want to get the value from input1, reverse the text and put it into input2 then just remove the first and last line of the code below
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

passing names into an array and sorting them

what im tryng to do is enter a first and last name into a textarea, once the "enter name" button is hit the names will go into an array, where they are sorted, then put back into a string and displayed in the "output" box. everytime a name is entered it will be added into the same array and sorted.
I was able to get the names into an array, and displayed in the output box, but i cant get it to add names to the list, or sort them alphabeticly. it just replaces them. I thought i could use push to add the names, but it doesnt seem to work. Any help would be very appreciated. Thanks in advance.
here is what i have so far:
<body>
<p>
<label for="name">Enter First and Last Name: </label>
<input id="name" name="name" />
<input type="button" id="addNameBtn" value="Enter Name" />
<input type="button" id="clearBtn" value="Clear Output" />
</p>
<p>
<label for="output">Output:</label><br />
<textarea cols="20" rows="15" id="output" ></textarea>
</p>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">grabText();</script>
</body>
</html>
`function grabText(){
var arr = [];
var arr2 =[];
var len = arr.length;
for (var i = 0; i<len; i++);
{
var txt = document.getElementById('name').value;
var textArea = document.getElementsByTagName('textarea');
if (txt !=="")
{
arr.push(txt);
}
}
arr2.push(arr);
arr2.sort();
var arrStr = arr2.join();
textArea[0].value = arrStr;
document.getElementById('name').value = '';
}
var btn = document.getElementById('addNameBtn');
btn.onclick = grabText;`
Playground
var textArea = document.getElementById('output');
var name = document.getElementById('name');
var btn = document.getElementById('addNameBtn');
var arr = [];
// Why whould you need arr2? to store the original?
function grabText(){
var txt = name.value;
if (txt !==""){
arr.push(txt);
}
arr.sort();
var arrStr = arr.join();
textArea.value = arrStr;
name.value = '';
}
btn.onclick = grabText;
A few things:
The for statement for (var i = 0; i<len; i++); - notice the very last character - a semi-colon. This for statement does very little - it evaluates and increments i, not the statements which follow.
var len = arr.length; syntax is correct, but the problem is arr is declared immediately before it and has a length of zero.
var arr2 stores the contents between invocations, but it has function scope and needs to be moved outside of the grabText function.

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources