I'm just starting to play around with JavaScript and Jquery and have hit a roadblock. I want users to be able to add & subtract boxes and fill it with input. Here's my html
<body>
<h1>Math Grades</h1>
<div id="mathGrades">
<input style="height:50px; width:50px; font-size:16pt; text-align: center" type='number' id="fooBar">
<input style="height:50px; width:50px; font-size:16pt; text-align: center" type='number' id="fooBar">
</div>
<button type="button" id="addBox">+</button>
<button type="button" id="subtractBox">-</button>
<br>
<button type="button" id="getGrades">Submit Grades</button>
<script src="calcjq.js"></script>
Here's my code:
$(document).ready(function() {
var addMathBox = document.getElementById("addBox");
addMathBox.addEventListener('click', addBox, false);
var subtractMathBox = document.getElementById("subtractBox");
subtractMathBox.addEventListener('click', subtractBox, false);
var getScores = document.getElementById("getGrades");
getScores.addEventListener('click', getUserGrades, false);
function getUserGrades(){
var userGrades = document.getElementById("fooBar").value;
console.log(userGrades);
}
function subtractBox(){
$('#fooBar').remove()
}
function addBox(){
$('#mathGrades').append('<input style="height:50px; width:50px; font-size:16pt; text-align: center" type="number" id="fooBar">')
};
});
How can I make sure to gather all of the input without knowing how many boxes they'll add and fill?
EDIT
Finally found a way to do this:
var mathGrades = $("input[class='mathGrades']")
.map(function(){return parseInt($(this).val(), 10);}).get();
First of all, and you probably know this but I wanted to point it out any way, your id attribute should be unique for each element. So make sure it's not foobar for all of them.
What you could do to solve your problem is add a unique class, i.e. mathGrades, to each input and then use the following code to collect all of the data and do as you please with it.
var mathGrades = document.getElementsByClassName('mathGrades');
var m, v;
for(m in mathGrades) {
v = $(mathGrades[m]).val(); // takes value and converts to string i.e. "1"
$(mathGrades[m]).val(v+1); // assigns new value "1" + "1" = "11"
}
In your javascript you could change the function addBox to:
function addBox() {
$('#mathGrades').append('<input style="height:50px; width:50px; font-size:16pt; text-align: center" type="number" class="mathGrades">')
};
Related
I have dynamically created inputs via a button, two get created at a time and I'd like the focus to be on the first of the two each time a set is added, so theoretically it'll always be the second last input
I currently use $('input:text:visible:first').focus(); but is there a way to do this but get the second last?
Input1.1
Input1.2
Input2.1
Input2.2
# user creates new input set via button
Input3.1 <---Focus on this one
Input3.2
One solution is to use eq(-2).focus(); (eq() documentation). From there you can read that the argument can be a negative number that represent the next:
indexFromEnd / Type: Integer / An integer indicating the position of the element, counting backwards from the last element in the set.
I have made a simple example to demostrate his use:
$("#myBtn").click(function()
{
$('<input value="new">').appendTo(".wrapper");
$('<input value="new">').appendTo(".wrapper");
$(".wrapper input").eq(-2).focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<input type="text" value="input1">
<input type="text" value="input2">
<input type="text" value="input3">
<input type="text" value="input4">
</div>
<button id="myBtn">ADD</button>
You can use input:nth-last-child(n) where n is any number
function createInput() {
let str = `<div class ='ipCon'>
<input type='text'>
<input type='text'>
<input type='text'>
</div>`;
document.getElementById('con').innerHTML = str;
document.getElementsByClassName('ipCon')[0].querySelector('input:nth-last-child(2)').focus()
}
input:focus {
background-color: yellow;
}
<div id='con'>
</div>
<button type='button' onclick='createInput()'> Create Inputs</button>
I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}
How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change
I'm having a listBox, when selected it, it will be printed in the textArea and beside to it I have given a clear button, so when clicked the value of the textArea has to be cleared, it works fine, now the problem is, after clearing the value in textArea and again when i select the listBox, the value is not getting printed on the textArea. What might be the problem?
Here is the code,
HTML:
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
JavaScript:
function addToExpText() {
alert("hello);
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
obj.appendChild(openP);
}
function clearTextArea(){
document.form1.textArea.value='';
}
After clearing the value in the textArea, again if i click on the listBox value and add it, it is not getting added. Pls help... Here is the implementaiton which is not working properly, may be its becaus i'm using it for the first time and i might be wrong.
http://jsfiddle.net/8dHf5/5/
Not sure why it works like that, but here are few possible fixes:
Instead of using append (to add a new aggregation function), you can use value both to add and clear:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId").value += aggreFunct;
}
function clearTextArea(){
document.getElementById("expTextId").value='';
}
Demo: http://jsfiddle.net/8dHf5/17/
Or you can use remove child nodes to clear values of textarea:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var myNode = document.getElementById("expTextId");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
Demo: http://jsfiddle.net/8dHf5/14/
Besides, there is a line obj.appendChild(openP); in your code, but I do not see it being available in code, so I removed it.
Another moment: in your clearTextArea you are trying to access your textarea like document.textArea - if I'm not missing something, it is IE only feature and it works with ids instead of names. It is better to use document.getElementById which is cross browser.
There was some mistake in your code.
I have modified it...
Now you are able to clear data.
Please refer below code:
<html>
<body>
<script>
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var textArea = document.getElementById("expTextId");
while (textArea.firstChild) {
textArea.removeChild(textArea.firstChild);
}
}
</script>
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
</body>
</html>
For instance, I know that it is possible to do something in Javascript that allows users to update text based on user text input:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>
View the above code in action at: tizag.com/javascriptT/javascript-innerHTML.php
However, instead of the above code, I would like to know if it's possible to do something similar for a url link. Below I've placed a step by step example of what I would like to happen upon the user inputing text:
Original Link:
http://www.google.com/search?q=
User Input in Text Field:
espn
User clicks button to submit text in text field
Final Link:
http://www.google.com/search?q=espn
Thanks for your help...BTW...if you can't tell I'm a bit of a novice so detail is appreciated.
Here's one in plain JS that updates as you type:
<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>
<script type="text/javascript">
var link= document.getElementById('reflectedlink');
var input= document.getElementById('searchterm');
input.onchange=input.onkeyup= function() {
link.search= '?q='+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
Note:
no inline event handler attributes (they are best avoided);
assigning both keyup and change, to try to get keyboard updates as they happen and ensure that all other updates get caught eventually;
the use of encodeURIComponent(), necessary in case the search term has any non-ASCII or URL-special characters in;
setting the search property of a Location (link) object to avoid having to write out the whole URL again;
setting the data of the Text node inside the link to reflect the full URL afterwards. Don't set innerHTML from user input as it may have HTML-special characters like & and < in.
#1: you need some forms
#2: you need to catch when the form is submitted
#3: based on the form's submission change the url
Here is a demo: http://jsfiddle.net/maniator/K3D2v/show/
here is the code: http://jsfiddle.net/maniator/K3D2v/embedded/
HTML:
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>
JS:
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e){
location = "http://jsfiddle.net/maniator/K3D2v/show/#"
+ encodeURIComponent(theInput.value);
return false;
}
I'd suggest using a cross browser library such as jQuery rather than straight JavaScript. With jQuery, you'd add a click handler for your button, grab the value of the input, build your URL, and set window.location to go to the new url
jsFiddle
HTML
<input type="text" id="q" />
<input type="button" id="submit" value="submit" />
JavaScript
$(function () {
$('#submit').click(function() {
var url = "http://www.google.com/search?q=";
url += $('#q').val();
window.location = url;
});
});
You could try this;
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
</script>
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value='Enter Search String Here' />
<input type='button' onclick='changeText2()' value='Change Link'/>
Check it out here
This is the solution I deviced in a matter of seconds:
<input type="text" name="prog_site" id="prog_site" value="http://www.edit-me.com" />
Open URL
No complex javascript, no extra quotes nor functions required. Simply edit the ID tag to your needs and it works perfectly.
I think this might be useful:
.btn {
border: none;
outline: 0;
display: inline-block;
padding: 10px 25px;
color: black;
background-color: #ddd;
text-align: center;
cursor: pointer;
}
.btn:hover {
background-color: #555;
color: white;
}
.textinput {
line-height: 2.5em;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
</head>
<body>
<form action='#' method='post'>
<label for='ytid'>Please enter your YouTube Video ID:</label>
<br>
<br>
<iframe
href='#'
width='287.5'
height='250'
frameborder='0'
allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture'
allowfullscreen
src='https://www.youtube.com/embed/'
id='ytvid'
></iframe>
<br>
<br>
<input
type='text'
class='textinput'
size='50'
id='ytid'
name='ytid'
placeholder='m4jmapVMaQA'
minlength='1'
maxlength='11'
onchange='document.getElementById("ytvid").src = "https://www.youtube.com/embed/" + this.value'
>
<br>
<br>
<button type='submit' class='btn'>Generate Subtitles »</button>
</form>
</body>
</html>
WARNING:
This code snippet might not run well in Stack Overflow.
This way, the video updates every time there is a change in the text input.
I'm actually making a YouTube Video subtitle generator, so I just copy pasted my code here.
www.google.com/search?q=<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
//changing the href of tag <a> by concatenatinng string "www.google.com/search?q=" and input (user input)
document.getElementById("link").href = "www.google.com/search?q="+input;
//changing the text from "www.google.com/search?q=" to "www.google.com/search?q=" + user input
document.getElementById("link").innerHTML = "www.google.com/search?q="+input;
}
Clicking the button calls the function changeText2. Which performs the task.