I'm trying to put together multiple user inputs and then combine them into one textarea after button click.
For example:
User1:Hey, I just met you
User2:And this is crazy
User3:But Here's my number so call me maybe
Combined Result:
Hey, I just met you, And this is crazy, But Here's my number so call me maybe
Here's my code the button click is currently not working but when I tried it before it did work so I was thinking I have some problem w/ my Jquery that triggers this unusual result:
HTML and Imports:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input class="combine" id="input1" disabled="true"></input>
<input class="combine" id="input2" disabled="true"></input>
<input class="combine" id="input3" disabled="true"></input>
<input class="combine" id="input4" disabled="true"></input>
<input class="combine" id="input5" disabled="true"></input>
<input class="combine" id="input6" disabled="true"></input>
<input class="combine" id="Voltes5" disabled="true" size="45"></input>
<button id="setVal">Set</button>
Jquery
$(document).ready(function(){
$('#setVal').on('click',function(){
jQuery(function(){
var form = $('.combine');
form.each(function(){
$('.Voltes5').append($(this).text()+ ' ');
});
});
});
});
Update for sir Arun P Johny
User1: If theres a (no comma when combined)
User2: will
User3: there's a way
Combined Result:
If theres a will, there's a way
Try
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.combine').not('#Voltes5');
var vals = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(vals.join(', '))
});
});
Demo: Fiddle
Here's a one-liner for non-readability ;)
$('#setVal').click(function(){$('#Voltes5').val($('.combine').not('#Voltes5').map(function(){return $(this).val();}).get().join(''))});
Expanded:
$('#setVal').click(function(){
$('#Voltes5').val(
$('.combine')
.not('#Voltes5')
.map(
function(){
return $(this).val();
})
.get()
.join('')
);
});
Get fiddly with it: http://jsfiddle.net/ArtBIT/u57Zp/
Here is one way to do this:
$('#setVal').on('click', function () {
$(".combine[id^=input]").each(function () {
if(this.value) {
$("#Voltes5")[0].value += ' ' + this.value;
}
});
});
There are several different ways to do this..
I'd do it this way using an array:
$(document).ready(function () {
$('#setVal').on('click', function () {
//create an array for the values
var inpAry = [];
$('.combine').each(function () {
//add each value to the array
inpAry.push($(this).val+' ');
});
//set the final input val
$('#Voltes5').val(inpAry);
});
});
but you would need to remove the combine class from #setVal because that would be included in the .each.
This way it would also be possible to have the final box updated on keyup as I'm not just appending the values, the combined values are set each time.
$(document).ready(function(){
$('#setVal').on('click',function(){
var val='';
$('.combine').not('#Voltes5').each(function(){
val+=$(this).val();
});
$('#Voltes5').val(val);
});
});
.text() will give text of the element ,for input val u have to use .val()
So there's immediate big problem in the code, which is that you're referring to your Voltes5 element as a class, not an ID. The jQuery selector you want is:
#Voltes5
instead of:
.Voltes5
There are a few other things to think about too, though, for the sake of functionality and best practices. Firstly, the Voltes5 element also has class combine, meaning that the $('.combine').each() call will include this element. The outcome of this is that it will also append its current text to itself when the code is run (or, when the code is run with the above correction).
When grabbing the current entered text of an input element, a jQuery .val() call is what you want, not .text() - see this answer for some more discussion.
Another thing that could be noted is that you should really explicitly specify what sort of input these elements are; <input type="text"> is hugely preferable to <input>.
Finally, input is a void element (reading), meaning it shouldn't have any content between opening and closing tags. Ideally, you wouldn't even give a closing tag; either have just the opening tag, or self-close it:
<input>
<input />
HTH
replace $('.Voltes5').append($(this).text()+ ' ');
with
$('#Voltes5').append($(this).text()+ ' ');
Related
I have a input field which is a percent value, i am trying for it to display as % when not focused in and when focused in it will loose the %, also the input field needs to avoid chars on it. I'm using a type"text" input field with some jQuery.
$(document).ready(function() {
$('input.percent').percentInput();
});
(function($) {
$.fn.percentInput = function() {
$(this).change(function(){
var c = this.selectionStart,
r = /[^0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
$(this).focusout(function(){
$(this).val(this.value + "%");
});
$(this).focusin(function(){
$(this).val(this.value.replace('%',''));
});
};
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2"></input>
<input class="percent" value="4"></input>
on the snippet it does not behave the same as on my app, not sure why but the intended result is for it to erase any char that is not a digit or "only" 1 % sign.
Would change this approach only slightly:
use keypress (and eventually paste) to block invalid characters
use parseFloat (or int if you don't allow decimals) to remove leading 0's --> '00009.6' => '9.6%'
However I'd use <input type="number"> (btw: </input> closing tag is invalid HTML)
these days with a % sign just after the input. (number type has better display on mobile)
(function($) {
$.fn.percentInput = function() {
$(this)
// remove formatting on focus
.focus(function(){
this.value = this.value.replace('%','');
})
// add formatting on blur, do parseFloat so values like '00009.6' => '9.6%'
.blur(function(){
var r = /[^\d.]/g,
v = this.value;
this.value = parseFloat(v.replace(r, '')) + '%';
})
// prevent invalid chars
.keypress(function(e) {
if (/[^\d.%]/g.test(String.fromCharCode(e.keyCode)))
e.preventDefault();
});
};
})(jQuery);
$(document).ready(function() {
$('input.percent').percentInput();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2%">
<input class="percent" value="4%">
It is my understanding that the snippet you provided is the desired behavior, but your app isn't behaving in the desired way you've demonstrated. So, the question is: what's different between this snippet and your app? Does your app throw any errors into the console?
When I encounter problems like this, I'll usually run my page through an HTML validator. Sometimes, invalid html can corrupt more than you'd think.
When I put your html into a standard HTML5 template, the validator finds these errors in your snippet:
Basically, it is saying that you don't need </input>. Do this instead:
<input class="percent" value="2">
<input class="percent" value="4">
Perhaps this is completely unrelated, but I thought I'd mention it. I'd put your actual app through the html validator to see if you find more errors that could be ultimately corrupting your javascript's ability to achieve the desired behavior showcased by your snippet.
I have multiple text inputs that all share the same class name.
Assuming the code has been written so that only one of those text inputs can have value at any one time, is it possible to search for the value of those text inputs by class name and only return the value of the one that has data written in it by the user?
For the purpose of this question, how would I get that value to be returned in the alert box in the code below?
var input = document.getElementsByClassName("input").value;
alert("input");
If it isn't possible using class names, is there an alternative solution that would achieve the same effect?
I would rather avoid having to give each text input an id and write code for each one, hence wanting to use class names.
//find all the elements, filter out the ones without a value, get the value
$('.theClass').filter(function(){ return this.value.trim(); }).val()
var $inputs = $('.aClass');
$inputs.on('input', function(){
$inputs.not(this).prop('disabled', this.value.trim());
});
$('button').on('click', function(){
console.log(
$inputs.filter(function(){ return this.value.trim(); }).val()
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><button>Get Value</button></div>
Please try this below code,
var matches = document.getElementsByClassName('input');
for (var i=0; i<matches.length; i++) {
//do action
console.log(matches[i].value)
}
Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;
what i need
i need to fetch hidden element data according to particular element id.
a.html
<input type="hidden" id="evt_date" value="feb 10">
<input type="hidden" id="evt_date" value="Mar 21">
<input type="hidden" id="evt_date" value="april 05">
js
<script>
$.each($('input'), function(i, val) {
if ($(this).attr("type") == "hidden") {
var event_date = document.getElementById('evt_date');
console.log(event_date);
}
});
</script>
problem
on doing console.log im getting
<input type="hidden" id="evt_date" value="feb 10">
i want to fetch all hidden element in loop using js.
updated js code
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$('.event_date').val();
console.log(evt_date);
$('.date_event').html(evt_date);
}
});
It's not a good practice to use same id for multiple element. You can instead use class attribute. So first you should change those repeated id attributes into 'class' attributes.
HTML : Updated
<input type="hidden" class="event_date" value="feb 10">
<input type="hidden" class="event_date" value="Mar 21">
<input type="hidden" class="event_date" value="april 05">
<div class="date_event"></div>
<div class="date_event"></div>
<div class="date_event"></div>
Next about your answer, loop through the each element and log the value or use it anyway. Try this,
jQuery :
You question seemed little confusing to me when in one part you asked for the data of the element and in another part you asked for the element itself.
$.each($("input[type='hidden'][class='evt_date']"), function(){
console.log($(this).val()); // value of the element
console.log($(this)); // the element itself
});
jsFiddle
Modification of your code :
jQuery :
var counter = 0;
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$(this).val();
console.log(evt_date);
$('.date_event:eq('+ counter +')').append(evt_date);
counter++;
}
});
jsFiddle
Dont know why you used same Id but this will be the short way:
$("input [id='evt_date'][type='hidden']").each(function(){
console.log($( this ))
});
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
console.log($(this).val());
}
});
Demo
Try this
$('input[type="hidden"]').each(function(index,item){
console.log($(item));
});
Working demo
You are using the same id for all the inputs. The id should be unique. Use a class instead
$.each($('input.evt_date'),function(i, field) {
if($(this).attr("type")=="hidden") {
console.log(field);
}
});
I want to place a cross button next to a text field, which, on clicking it, clears the value entered by the user. In other words, it empties the field. Please help..
And I also want to focus the field, but after some 2 or 3 seconds..
Like this:
$('#myButton').click( function () {
$('#myField').val('');
});
Or without jQuery
document.getElementById('myButton').onclick = function () {
document.getElementById('myField').value = '';
});
Try this,
$('#button').click(function(){
$('#inputBox').val('');
});
Have you tried anything at all? But this should do (edit after misread, see below):
$('#your_button').click(function() { $('#your_textbox').val(''); });
In Javascript:
document.getElementById('textField1').value = "";
Well, learn to break your tasks into smaller one and everything will become much easier. Here, for example, you have 2 tasks:
1) Place a "X" button near input. This is achieved by CSS and HTML. You HTML might look like:
Then you should align your image with you input
2) Actual erasing. In jQuery:
$("#x_button").click( function() {
$("#input_id").val( "" );
});
But this is real basics of web development, so you should really consider to read some kind of book on it.
You can do it with html5 value.
<input type="text" placeholder="Your text here">
Assuming your text field looks like this one :
<input type="text" id="myText"></input>
and your button looks like this one :
<input type="button" id="myButton"></input>
You just have to do this in javascript :
<script type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.addEventListener("click", function () {
document.getElementById('myText').value = '';
}, false);
</script>
If you're using jQuery it's even easier :
<script type="text/javascript">
$('#myButton').click(function() {
$('#myText').val('');
});
</script>
here is a sample:
Html:
<input type="text" id="txtText" value="test value" />
<input type="button" id="btnClear" value="Clear" />
javascript:
$(document).ready(function () {
$("#btnClear").click(ClearText);
});
function ClearText() {
$("#txtText").val("");
}