Jquery Not working to create new Inputs - javascript

Below is my Html Doc and the JQuery does not do anything when the range input changes, any assistance is much appreciated as I am extremely new to web design. Even the alert doesn't work at the top so I am unsure as to what my problem is. My belief is somehow the script is never being called or it's a problem with it being an html doc but either way thank you.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var num=0;
var numOptions = new Array(100);
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function(){
$("#numQuestions").on('input',function(){
var numbQuestions = $("#numQuestions".text());
if(num>numbQuestions){
for(i=numbQuestions;i<=num;i++){
try{
$("#qRowNum'+i).remove();
}catch(err){
}
}
}else{
for ( i=num; i < numbQuestions; i++)
{
var row = '<div id="qRowNum'+ i '">
#the below function is not implemented in this version
<input type="text" placeholder="Question '+i'"> <input type="range" name="numOptions'+i'" min="0" max="5" placeholder="Number Of Options" onchange="CreateOptions(this);" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();> </div>';
$("#questionRows").append(row);
//New script test
}
}
num = numbQuestions;
});
});
<div id="questionRows">
</div>
<input type="submit" value="Start">
</form>
</body>
</html>

This is your problem:
var numbQuestions = $("#numQuestions".text());
Firstly I think you mean this:
var numbQuestions = $("#numQuestions").text();
But that is also not true because an input field has not text property. They have value So do this:
var numbQuestions = $("#numQuestions").val();
And this is another problem: $("#qRowNum'+i) When you start selector by double quotation, you need to end this also by double quotation. But it still is not a true jquery selector.
I think you need to more studies about jquery.

Related

How to select and run this function onload?

So I have this working codeblock in my script to replace the decimal seperator from comma "," into period "." ,when editing a form. Because in this region the decimal seperator comma is normal I also want the values to be displayed like this 1,99€ so I reverted the working function. The selected fields should change on load. When the form gets submitted I will cange it back again. For this example I show you only one of the fields.
The value="1.5" gets loaded from the Magento-Backend the wrong way, which is another story:
I included onload:"function(event)"
and window.onload = function(); to show two my attempts to adress this function from jQuery: jQuery('form').on('change', '#price', function(event) I also need to know how to remove the .on('change' part. First time using Js und jQuery. I really tried everything.
<html>
<body onload="function(event)">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>
<script>
window.onload = function();
jQuery('form').on('change', '#price', function(event) {
event.preventDefault();
if (jQuery('#price').val().includes('.')) {
var varwithpoint = jQuery('#price').val();
varwithcomma = varwithcomma.replace(",",".");
jQuery('#price').val(varwithpoint);
}
else {
console.log('no dot to replace');
}
});
</script>
There were a few parts of the code which didn't seem to be working as intended, so below is a basic example of code that will convert the "," to a "." if stored in the input "price", and check this after each change of the value;
function convert_price(){
var this_price = $("#price").val();
if (this_price.includes(',')) {
this_price = this_price.replace(",",".");
$('#price').val(this_price);
} else {
console.dir('no dot to replace');
}
}
convert_price();
$("#price").on("change",convert_price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body>
<form>
<input id="price" value="1,5">
</form>
</body>
</html>
I have called "init" the function that attaches the change event to the input file, I also changed the parameters passed to the on function
function init(){
var input = jQuery('#price');
input.on('change', function(event) {
event.preventDefault();
var valueInInput = input.val();
if (valueInInput.includes('.')) {
var varwithcomma = valueInInput.replace(",",".");
input.val(varwithcomma);
} else {
console.log('no dot to replace');
}
});
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="init()">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>

Clearing the field of a form with a button

Sounds easy probably, but not for a beginner programmer :)
I have a simple 3 field form with a submit button and a clear button. This is for a homework assignment, and we have been tasked to get the "Clear Fields" button to work properly. Here are more specific instructions:
"Add the JavaScript code for an anonymous function that's stored in a variable named clear. The function should clear the text boxes by using the $ function to get a Textbox object for each text box and then setting the value property of the textbox to an empty string. Then, add a statement in the onload event handler that attaches the clear function to the click event of the Clear Entries button."
I was able to add the statement to the onload event handler:
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
But it is the other part I am having problems with.
Add the JavaScript code for an anonymous function that's stored in a variable named clear:
var clear = function () {
Object.Method
}
Here is my full code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
var clear = function () {
miles.Text = String.Empty
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label> </label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
And here is the code we were supplied with to work off of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</section>
</body>
</html>
You've got several issues going on:
You're mixing Javascript and jQuery in ways that don't quite work.
jQuery's methods and objects work differently than "pure"
Javascript, so be mindful of that.
The window.onload doesn't work the way you've got it. To be
consistent, do it the jQuery way with a $(document).ready() method
instead.
You're missing the # indicator on your jQuery IDs. This is
imperative or it won't find the ID of the elements you're calling.
It looks like you're mixing VB/C# code in with your javascript, such
as the String.Empty call, etc. Those objects/methods work from the
server and not in Javascript, so that's another issue (it's been a
while since I've worked in C#, so double check me on that).
Here's my solution below. I tweaked a few things to help with what I think you're going for (such as clearing ALL fields with the "Clear" button instead of just the miles field).
I understand you're a student, so don't make it a habit of coming here and trying to find people to do your homework for you. You did provide an attempt at some code, and there were a number of issues in it, so I chose to rectify them for you and explain the reasons since there were so many. Others are not as generous, but I was a struggling student once, too, so I get it when you're banging your head against the wall. :-)
$( document ).ready( function () {
var clear = function () {
miles.value = "";
gallons.value = "";
mpg.value = "";
}
var calculateMpg = function () {
var miles = parseFloat($("#miles").val());
var gallons = parseFloat($("#gallons").val());
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");
}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");
}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");
}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("#mpg").val(mpg.toFixed(1));
}
}
$("#calculate").bind("click", calculateMpg);
$("#miles").focus();
$("#clear").bind("click", clear);
});

How to clear and replace the contents of an input field with the value of a button?

I think there is an easy solution however I have searched and cant seem to find he answer. I am trying set up several buttons that when pressed replace the the contents of an input field with the value of the button. I would prefer to control this with pure javascript rather than jquery if possible.
Also, if possible I would like the title of the button to be slightly different than the value it passes to the input field.
One way to do it
script:
function foo(id, el)
{
document.getElementById(id).value = el.innerHTML.replace(/test/, 'something');
}
(Obviously you'd want to do something more useful to the value than replacing test by something. But you can.)
html:
<input id="piet"/>
<button onclick="foo('piet',this)">test123</button>
<button onclick="foo('piet',this)">test234</button>
http://jsfiddle.net/sE2UV/
Assume this markup (an extra data attribute to avoid hardcoding the selector):
<input id="target" type="text">
<button value="potatoes" data-for="#target">Potato</button>
<button value="tomatoes" data-for="#target">Tomato</button>
You may use value attribute to store the data:
var buttons = document.querySelectorAll('button[data-for]');
for (var i = 0; i < buttons.length; i++) {
var targetId = buttons[i].dataset.for;
var target = document.querySelector(targetId);
buttons[i].addEventListener('click', function () {
target.value = this.value;
})
}
Demo: http://jsfiddle.net/dmu8N/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function setText() {
document.getElementById("input1").value = "SOME TEXT";
}
</script>
</head>
<body>
<button type="button" onclick="setText()">Click me to set text!</button>
<input id="input1" type="text">
</body>
</html>
Full JSBin Example: http://jsbin.com/aZIyAzir/2/
Here's a jQuery solution for completeness.
<input type='text' id='target'></input>
<button>Merry</button>
<button>Christmas</button>
Then your jQuery:
$(function() {
var $target = $('#target');
$('button').on('click', function() {
$target.val($(this).html());
});
});

Build, Modify, Output Javascript Array

I'm trying to accomplish the following...if it's asking too much in a single question then some simple steps on what events to use will still help.
There are 2 blank textareas sitting next to eachother - Input and Output. Between them are two inputs Before and After. I want to type or paste a list of words into Input separated by line break, for example:
melons
peaches
apples
And then use the Before and After inputs to add in a word/phrase/symbol before and after each keyword. So if I type 'buy' in before and 'today' in after, the Output text area will display:
buy melons today
buy peaches today
buy apples today
I'd like to accomplish this without having any page refreshing. We can assume the form elements are named as follows:
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
I've been try to at least get the Input text to display in Output using this code, but that's not even working:
$(document).ready(function(){
$('#input').keyup(function(e){
$('#output').html($(this).val());
});
});
Any guidance would be awesome!
a compact one:
$("#input,#before,#after").on("keyup", function () {
$("#output").val(
$.map($("#input").val().split("\n"), function (n, i) {
return $("#before").val() + " "+ n + " " + $("#after").val();
}).join("\n"));
});
example
This would do the trick:
function update_output(){
//Split input by newline
var input_words = $('#input').val().split('\n');
var output_lines = new Array();
//Iterate over each keyword and prepend and append values
$.each(input_words, function(i, word){
output_lines.push($('#before').val()+' '+word+' '+$('#after').val());
});
//Display output in textarea
$('#output').val(output_lines.join('\n'));
}
You just need to choose when you want to update the output textarea, maybe bind it so it updates every time the #input or #before and #after changes:
$('#input,#before,#after').on('change',update_output);
Alright, I can help you to get started. My answer is not complete, but you can have a very good idea from here. Note I wrote this code to be easy to understand and I am not using sophisticated approaches on purpose.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#input").keypress(function(key){
if(key.which == 13) {
refreshData();
}
});
});
function refreshData() {
var beforeVal = $("#before").val();
var inputLines = $("#input").val().split(/\r\n|\r|\n/g);
var desiredOutputVal = "";
for(var i=0; i<inputLines.length; i++) {
desiredOutputVal += beforeVal + inputLines[i] + "\n";
}
$("#output").val(desiredOutputVal);
}
</script>
</head>
<body>
<form>
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
</form>
</body></html>

How do I get the first child of each of these rows?

I have 2 rows, each with 2 text inputs. How do I go through each row w/ class "myRow" and, within each row, get the first child that has class "This"? I can get the first "This" class of row 1 but can't seem to get row 2.
My fiddle
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This").eq(0).val();
alert(r);
});
});
});
</script>
</head>
<body>
<div class="myRow">
<input type="text" class="notThis" value="wrong!"/>
<input type="text" class="This" value="first one!"/>
<input type="text" class="This" value="almost!"/>
</div>
<br>
<br>
<div class="myRow">
<input type="text" class="notThis" value="wrong!"/>
<input type="text" class="This" value="second one"/>
<input type="text" class="This" value="almost!"/>
</div>
<button id="btn">Submit</button>
</body>
</html>
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This:first", this).val();
alert(r);
});
});
$('.This:eq(0)','.myRow').css('background-color','#F00');
$('.myRow').find('.This:eq(0)').css('border-color','#F00');
$('.This:first','.myRow').css('color','#0F0');
$('.myRow').find('.This:first').css('font-weight','bold');
Working example
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This", this).eq(0).val();
alert(r);
});
});
To get both in a selector, you could always do:
var elems = $('.This:eq(0)', '.myRow');
Then you could do this to get an array of the values:
var values = $.map($('.This:eq(0)', '.myRow'), function(el) {return el.value});
FIDDLE
Change to:
Demo
var r = $(this).find(".This").eq(0).val();
You need to look for .This relative to the current element, otherwise it will always find the first instance.
Side note: as an alternative to .eq(0) you can use .first().
You can get an array of JavaScript objects by using jQuery's factory method to search for a certain property. Example:
var search = $('input[class="This"]');
You can access the first one found by simply using:
search[0];
Essentially (and this is not the most optimized way of doing it), you can do this:
var rows = $('.myRow');
for(var i = 0; i < rows.length; i++) {
var first;
var row = $(rows[i]);
var children = row.find('input[class="This"]');
// You can also do row.find('input.This');
if(children.length > 0) {
first = children[0];
// Do something with it
}
}
Like I said, not the most optimal way, but each time you use the factory method, you're getting an array of objects and you can loop through them.
You can search through HTML properties like the above.
Examples:
$('input[type="button"]')
$('input[name="firstName"]')
$('a[href="www.google.com"]')
This should do the trick:
$('#btn').click(function(){
$(".myRow input:nth-child(1)").each(function(){
alert($(this).val());
});
});

Categories

Resources