I have a function that displays text in a div as its typed into an input. Right now it simply checks for each ID go get the value and display the text.
I want to make this function reusable so that I can match different inputs with different divs without writing a unique function for each case.
Here is an example that works using a single input and div:
<body>
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
And I want to be able to repeat this for different sets of unique inputs & divs with a reusable function.
<body>
<!-- First set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- Second set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- etc... -->
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
If you wrap each "set" in a container, and swap your ids for classes, you can can add listeners to each input to watch for changes, find the parent container, find the display box and update its text content.
// Get all of the inputs
const displayText = document.querySelectorAll('.inputBox');
// Attach listeners to all of them
displayText.forEach(input => {
input.addEventListener('keyup', handleChange, false);
});
function handleChange() {
// Find the closest div ancestor element (the container)
const parent = this.closest('div');
// Then locate the display box and update the text content
parent.querySelector('.displaybox').textContent = this.value;
}
.container { margin-bottom: 1em; }
.displaybox { margin-top: 0.2em; height: 1.3em; width: 300px; border: 1px solid black; }
<div class="container">
<input type="text" name="name" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="age" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="location" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
It seems you would need to get the ID of each input box and each output box?
function showTypedInput(inputID, outputID) {
var inputBox = document.getElementById(inputID);
var outputBox = document.getElementById(outputID);
inputBox.onkeyup = function(){
outputBox.innerHTML = inputBox.value;
};
}
Then you just reuse this?
showTypedInput("myInputBox", "myOutputBox");
You can create this functionality using following:
function listener(target){
return function(e){target.innerHTML = e.target.value};
}
function init(){
var elems = document.querySelectorAll("input[data-keyuptarget]");
for(var elem of elems){
var target = document.getElementById(elem.getAttribute('data-keyuptarget'));
if (target) elem.onkeyup = listener(target);
}
}
init();
In html just use
<input type='text' name='name' data-keyuptarget="displayBox1">
<div id='displayBox1'></div>
<input type='text' name='name' data-keyuptarget="displayBox2">
<div id='displayBox2'></div>
JS Bin : https://jsbin.com/piwiyapohe/edit?html,output
Related
I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.
Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>
I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>
I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
this is my code but add button is coming of first field but i want that whenever a new input field came the add button shift next to the new input field.
function add(){
var new_chq_no = parseInt($('#total_chq').val())+1;
var new_input="<input type='text' id='new_"+new_chq_no+"'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no)
}
function remove(){
var last_chq_no = $('#total_chq').val();
if(last_chq_no>1){
$('#new_'+last_chq_no).remove();
$('#total_chq').val(last_chq_no-1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
Try This
var new_id = 0;
function add() {
new_id += 1;
var inp_div = document.getElementById("inputs");
var new_inp = document.createElement("input");
new_inp.setAttribute("id", new_id);
inp_div.appendChild(new_inp);
}
function remove() {
if (new_id >= 1) {
document.getElementById(new_id).remove();
new_id -= 1;
}
}
<div id="inputs">
<input type="text">
</div>
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
Try wrapping the button and the input in a div with css attribute display: inline-block
User specifies the quantity of new element (div) to be created and clicks on a button to create the number of elements. The Javascript code is working but I want to use jQuery. Help please!
HTML
Quantity of div: <input type="text" id="quantity" name="quantity" value=""><br /><br />
<button id="create" onclick="addFields()>Create</button>
<div id="container">
</div>
Javascript
function addFields() {
var number = document.getElementById("quantity").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Div "+(i + 1)));
}
}
How do I do it in jQuery? Thanks very much
Here's one way to let a user specify the number of divs to append to your container div using jQuery:
$('#create').click(function() {
for (var i = 0; i < $('#quantity').val(); i++) {
$('#container').append('<div>Div '+i+'</div>');
}
})
#container > div {
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Quantity of div: <input type="text" id="quantity" name="quantity" value=""><br /><br />
<button id="create">Create</button>
<div id="container"> </div>
The CSS is there to visualize the new divs. First you create a click handler and bind it to the button. Then when the button is clicked, it takes the value from the input and uses that to create a loop to append divs to your container.
I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them
I tried to make a function by passing an event to a button but it is not working. What I want the function to do is that when the button is clicked show in the DOM that I click and also display with the innerhtml a message on the web page using if/ else depending of the user imput in the imputs of time abd weight
$(document).ready(function() {
$('#calculate').on('click', function() {
$('#calculate ul li input').slideToggle(800);
});
/********************************************************/
var gender = $('#gender');
var age = $('#age');
var time = $('#time');
var weigth = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
if (calculate.lenght) {
/*event listener*/
calculate.on('click', calculateF);
/*para que cuando se haga click se active la funcion calcular
que estoy creando abajo*/
function calculateF(event) {
event.preventDefault();
console.log("click");
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" text ");
} else {
result.html("text");
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section id="calculate">
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--here comes the result-->
<div class="result" id="result">
</div>
.
You are missing the # if you have declared the time, weight, result, and calculate as id's of the elements that you are targeting.
From what I can guess is that the weight and time are inputs the result is a div and the calculate is the button to be clicked.
I will assume they are ids so you need to add # before the id when specifying selectors in jquery using $() otherwise use . if they are class names.
Then if you are converting the code to jquery from javascript you need to replace the respective functions like addEventListener .innerHtml , .value etc
You can see the working below but the calculations and the message that you have to add is on your end as you never provided any details so i have made the conversion for the code
$(document).ready(function() {
var time = $('#time');
var weight = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
/*event listener*/
calculate.on('click', calculateF);
function calculateF(event) {
event.preventDefault();
console.log("you hit click");
/*new variables*/
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" if condition true ").show();
} else {
result.html("message from the else part").show();
}
}
});
.result {
border: 1px solid #c7c7c7;
padding: 5px;
text-align: center;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--here comes the result-->
<div class="result" id="result">
</div>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section>
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--folder where my jquery code is saved-->
<script src="js/jquery.js"></script>
<!--folder where my jquery code is saved-->
<script src="js/scripts.js"></script>
EDIT
Your HTML has duplicate id calculate for the section and for the input button that's why it isn't working you cannot have multiple elements with the same id I have used your HTML and removed the id from the section tag, see the demo above