newbie here. My target is when is when I click the button, my 2nd textbox will do the copy without comma. How can I make this work? I provided my JS fiddle and codes below. Any help will be appreciated. Thank you
JS Fiddle: https://jsfiddle.net/rain0221/auk4rfdg/6/ // I provided more explanation here
html:
<input type="text" value="" class="form-control" id="box"/>
<input type="text" value="" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
script:
//this function copies the textbox1 values with autocomma and produces same value but without comma on textbox2
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
//this function shows the value of my button to the textbox
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
}
When 5000 clicked, change textbox2 value!
Code snippet:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
document.getElementById("textbox2").value=count.replace(',','');
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<input type="text" value="" class="form-control" placeholder="autocomma textbox" id="box"/>
<input type="text" value="" placeholder="same value but no comma" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
document.addEventListener("input", action)
document.addEventListener("click", action)
function action(ev){if (ev.target.tagName=="INPUT"){
const ch=ev.target.closest("div").children;
if(ev.target!=ch[1])
ch[1].value=(ev.target.value-0).toLocaleString()
if(ev.target==ch[2])
ch[0].value=ev.target.value;
}}
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="5000">
</div>
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="2000000">
</div>
I wrote my snippet without jQuery as it is not really needed here and I reversed the roles of the input fields as it is
a better user experience if the input is not tampered with directly
difficult to "undo" a .toLocaleString(), see here
The trigger for action is the input event which also includes paste actions done via mouse clicks.
I also removed the id attributes from your input values. This way you can add further input groups to your page and re-use the script without further change.
All my addEventListener() actions are done in the "delegated" mode, to the parent document. By doing it this way the event will also be triggered by dynamically added elements (elements that might get added through some user interaction).
Related
I'm very new to Javascript/JQuery and wanted to know how i can store the values of these Inputs:
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<input type="number" id="rooms_amount_bathrooms"autocomplete="off" value="0">
<input type="number" id="rooms_amount_kitchens" autocomplete="off" value="0">
inside this input <p> element:
<p class="chosen_service__room_types">""</p>
using pure Javascript. Thanks for the help!
You can add an Event Listener to the input and set its value in localStorage.
In case you want to update the storage every time the user inputs you can do this:
document.getElementById('rooms_amount_bedroom').addEventListener('input', function(){
let val = this.value;
localStorage.setItem('input',val)
})
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
In case you want to update the storage once on a button click:
document.getElementById('btn').addEventListener('click', function(){
let val = document.getElementById('rooms_amount_bedroom').value;
localStorage.setItem('input',val)
})
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<button id="btn">Update</button>
Then, on the other page, you can set the stored value to the paragraph's content on load as follows:
window.onload = function(){
document.getElementsByClassName('chosen_service__room_types')[0].innerHTML = localStorage.getItem('input');
}
<p class="chosen_service__room_types"></p>
Example 1. Using a link
page 1
Change WhateverItIsYouArClicking to #link if what you are clicking has id="link"
or ".someClass" if what you are clicking has class="someClass"
window.addEventListener("load",function() {
document.querySelector("WhateverItIsYouArClicking").addEventListener("click",function(e) {
e.preventDefault(); // if it is a link or a submit button
const fields = [...document.querySelectorAll("input[type=number]")].map(fld => fld.id+"="+fld.value);
location = "index.html?"+fields.join("&");
})
})
Page 2
window.addEventListener("load",function() {
const url = new URL(location.href);
document.querySelector(".rooms_amount_bedroom").textContent = url.searchParams.get("rooms_amount_bedroom");
document.querySelector(".rooms_amount_bathrooms").textContent = url.searchParams.get("rooms_amount_bathrooms");
document.querySelector(".rooms_amount_kitchens").textContent = url.searchParams.get("rooms_amount_kitchens");
})
Example 2 using a form
<form action="index.html">
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<input type="number" id="rooms_amount_bathrooms"autocomplete="off" value="0">
<input type="number" id="rooms_amount_kitchens" autocomplete="off" value="0">
<input type="submit" />
</form>
and on page 2 have the same as above
I want to create a dynamic questionnaire, loading the next question dynamically, but when I load the second question, the event of the button next2 doesn't respond as if there were no event.
I think it's because I load the input with a JavaScript function. What do I have to do to make it work?
$(document).ready(function() {
var question2 = `
<form>
<input type="number" id="age" placeholder="age">
<input type="submit" id="next2">
</form>
`;
var question3 = `
<form>
<input type = "email" id="email" placeholder="email">
<input type="submit" id="next3">
</form>
`;
$('#next').click(function(e) {
e.preventDefault();
console.log(1);
$(".questions").html(question2);
});
$("#next2").click(function(e) {
e.preventDefault();
$(".questions").html(question3);
});
$("#next3").click(function() {
alert('Cool');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="questions">
<form>
<input type="text" id="name" placeholder="Name">
<button type="submit" value="Next" id="next">Next</button>
</form>
</div>
</html>
You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","#idname",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click', '#next', function(e) {
e.preventDefault();
$(".questions").html(question2);
});
You only need one event handler for all this, not multiple.
You are inserting the HTML into the element with the class questions with $(".questions").html. Given that you should hook the event handlers to that element with the questions class to be as close to the element as possible (not make it traverse the entire DOM looking for things in the events.
Here I took the CURRENT html and saved it to myApp which I created to hold stuff and not pollute the global namespace; Then I cycle back to it on the last. Odd that you have both button and input type submit but I also handle that. Since these are submit buttons in a form, I added the submit event in case that is how it gets triggered.
$(function() {
let myApp = {};
myApp.question2 = ` <form>I am 2
<input type="number" id="age" placeholder="age">
<input type="submit" id="next2" data-nextthing="question3">
</form>
`;
myApp.question3 = ` <form>I am 3
<input type = "email" id="email" placeholder="email">
<input type="submit" id="next3" data-nextthing="question1">
</form>
`;
myApp.question1 = $(".questions").html(); // just to store it
$(".questions")
.on('click submit', 'form, button[type="submit"], input[type="submit"]', function(event) {
event.preventDefault()
let d = $(this).data('nextthing');
$(event.delegateTarget).html(myApp[d]);
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="questions">
<form>
<input type="text" id="name" placeholder="Name">
<button type="submit" value="Next" id="next" data-nextthing="question2">Next</button>
</form>
</div>
I want to pass the value 9112232453 of one textfield to another.
I know I need Javascript for this but I don't know how to do it.
HTML
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
Then later, I want to use the value in my php.
You could use a JS. function to take param (this.value) like:
<script>
var some_func = function (val){
var input = document.getElementById("phone");
input.value = val;
}
</script>
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func(this.value);' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
The best way is to not obtrude the HTML code with Javascript event handlers.
So, you can add a DOMContentLoaded event listener to the document, and as soon as DOM is loaded:
You add a change event listener to the input[type=checkbox], and then:
1.1. If the checkbox is checked, then you change the input#phone's value to its value
1.2. If not, then you empty the input#phone's value.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('cbphone').addEventListener('change', function(e) {
var phone = document.getElementById('phone');
if (this.checked) {
phone.value = this.value;
// you can even enable/disable the input#phone field, if you want to, e.g:
// phone.disabled = false;
}
else {
phone.value = '';
// phone.disabled = true;
}
});
});
<form method="post" action="">
<input type="checkbox" name="cbphone" id="cbphone" value="9112232453">
<input type="text" name="phone" id="phone">
<input type="submit" name="Go" value="Go">
</form>
before submit form use validation and check whether the field value is filled up or not. if yes get value of the field.
if(document.getElementBy("fieldIdfirst").value!="")
{
document.getElementBy("fieldIdSecond").value=document.getElementElementById("fieldIdfirst");
}
Thanks it..
Try this: http://jsfiddle.net/yhuxy4e1/
HTML:
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' id="chk_phone">
<input type="text" name="phone" value="" id="txt_phone">
<input type="submit" name="Go">
</form>
JavaScript:
some_func = function() {
var checkBox = document.getElementById('chk_phone');
var textBox = document.getElementById('txt_phone');
textBox.value = checkBox.value;
}
I have 2 textboxes with a type="number".
1 textbox is my 'master' textbox, then I have another subsequent textbox that I would like that IF the 'master' textbox is filled in with a number, the subsequent textbox would get the same value.
I thought about using the data- attribute but I am not sure how to target if the 'master' textbox is filled then, then subsequently put the same value in the sub textbox(es) with the same data- attribute.
In my example below I also use spans to create plus and minus buttons that adjust the value based on the value. This is in the JS section.
My current HTML is as follow:
<div id="masterTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
<!--Values from Master Textboxes should populate into these textboxes as well.-->
<div id="subTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
Javascript
<script>
$(document).ready(function () {
/*Add an minus buttons for variants*/
$(".AddMinusButton").on('click touchstart', function (event) {
event.preventDefault();
//Add button active style for touch.
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var newVal = oldValue;
//Hide .decButton for oldValue
if (newVal == 0 || oldValue == 0 ) {
oldValue = 0;
}
else { $button.parent().find(".minusBtn").show(); }
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// Don't allow decrementing below zero
if (oldValue >= 1) {
newVal = parseFloat(oldValue) - 1;
}
}
$button.parent().find("input.attendeeQuantityInput").val(newVal);
//Sub textboxes should take value of master textboxes. Is this correct syntax?
//This is probably wrong.
$('#subTextboxes input').data("attendee").val(newVal);
});//End button click
});
</script>
I hope this makes sense on what I am trying to get out of this.
Thanks in advance.
I would like that IF the 'master' textbox is filled in with a number,
the subsequent textbox would get the same value.
You can do it like this:
<p>
<label>Master 1: <input type="number" id="master1" placeholder="0" /></label><br>
<label>Dependant 1: <input type="number" class="dependant1" placeholder="0" /></label>
</p>
<p>
<label>Master 2: <input type="number" id="master2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label>
</p>
And in the JS:
$("input[id^='master']").on("change", function(){
var no = this.id.replace("master", "");
var selector = ".dependant" + no
$(selector).val(this.value);
});
This makes use of jQuery's attribute starts with selector and will work for any number of inputs provided the class names match.
Demo
You could do this:
HTML:
<div id="masterTextboxes">
<p>Master</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
<div id="subTextboxes">
<p>Sub</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
JS:
// On change in master inputs...
$("#masterTextboxes input", this).on("change", function() {
// Store Master inputs in master variable and Sub inputs in sub variable.
var master = $("#masterTextboxes input"),
sub = $("#subTextboxes input");
// Match master and sub values by using the master array key as reference.
$(sub[$.inArray($(this)[0], master)]).val( $(this).val() );
});
The jQuery code relies on the condition that the Sub inputs follow the same order as the Master's inside each respective div.
JSFiddle:
Here's a working JSFiddle for reference.
The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();