Firstly I wanna check the given value in textfield is Number or not.
But I have number of textfields ,the number is depending upon dynamic value from php&yii like as follows
<?php foreach($model->getData() as $donation){ ?>
Donation For <?php echo $donation['DonationName'];?>
<label><b>$</b> <input class="textfld3" style="width:75%" title="First Name" placeholder="Amount" type="text">
</label>
<?php } ?>
so I wanna get the value of the textfield or textfields in js..
I had also used the jsfunction as
var texts= $(".textfld3").map(function() {
return $(this).val();
}).get();
alert(texts);
but all the values are showing in alert box along with commas
how should i get the value of textfiled or textfields to check whether it is number or not in js.
Loop through all the textfield using $(".textfld3").each(function() { and find value of textfield one after another. If a textfield having a non numeric value then show alert message and will focus on that textfield.
$(".textfld3").each(function() {
var currentVal = $(this).val();
if(isNaN(currentVal)){
alert("Please enter numeric value");
$(this).focus();
return false;
}
});
From a quick view into your code, it looks to me, texts is an array, so you could run through this array
var texts= $(".textfld3").map(function() {
return $(this).val();
}).get();
for ( var i = 0; i < texts.length; i++ ) {
alert(texts[i]);
}
You have to pass key and value parameter in map function so you can return value of all text fields by value, here ele variable is value which is reference one element of that class selector
$("#btn").click(function(){
var texts= $(".textfld3").map(function(key,ele) {
return $(ele).val();
//return ele.value
}).get();
console.log(texts);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><b>$</b> <input class="textfld3" style="width:75%" title="First Name" placeholder="Amount" type="text">
</label>
<hr>
<label><b>$</b> <input class="textfld3" style="width:75%" title="First Name" placeholder="Amount" type="text">
</label>
<hr>
<label><b>$</b> <input class="textfld3" style="width:75%" title="First Name" placeholder="Amount" type="text">
</label>
<hr>
<label><b>$</b> <input class="textfld3" style="width:75%" title="First Name" placeholder="Amount" type="text">
</label>
<hr>
<button id="btn"> Get Values</button>
Related
So I'm having trouble with JS and how to correctly collect and pass all values from a text field and hidden field on a button click.
<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
Those are text fields and hidden fields with unique ids. They are 'connected'. When you change the value in the text field, the value in the hidden field changes automatically.
When you click on a button, then values that will be written in the text field should be processed in js
function room_group() {
$('.add').bind('click', function() {
var hidden_values = 'something here' // Let's get all values here and pass them to the get request
var values = 'something here' // Let's get all values here and pass them to the get request
$.post('/link/definition', {
val: values,
hidden_val: hidden_values
},
function(response) {
location.reload();
}
);
});
}
The question is how to collect all of those values correctly? Unfortunately, I have no idea...
It depends on how you want to format your values.
You can serialize the values by searching for them with an appropriate selector and then you can create a JSON string as value.
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text" value="t1" name="text1" />
<input type="text" value="t2" name="text2" />
Your POST will be something similar to:
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
$.post('/link/definition', {
val: textValues,
hidden_val: hiddenValues
},
function(response) {
location.reload();
}
);
I currently have an input type="text" that I transform into a currency value on the "keyup" event. In order to keep this functionality (works fine), the input type has to be set to "text". At the same time, I would like to have a minimum value of "100.00" set to it.
Any way I can accomplish this? Also, would I able to customize my jquery validation message to say "Minimum Amount $100.00"?
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required id="balance" name="balance" type="text" class="number" />
You can add this property in your input filed: minlength="5"
<input required id="balance" name="balance" type="text" class="number" minlength="5" />
And in your JS code you can add a 'if' statement to check that this input contain at least 5 char.
Furthermore you can add the same 'if' statement in your back-end to check it again.
Thank you all for your input.
I've ended up keeping the input type="text" for the number of digits users can type in and called a function to check the input value against the 100.
function checkAmount() {
var valueBalance = $("#balance").val();
var valueNumberBalance = parseFloat((valueBalance).replace(/[^\d\.]/, ''));
if (valueNumberBalance < 100) {
$("#balance").get(0).setCustomValidity("Minimum Amount of $100.00");
}
else {
$("#balance").get(0).setCustomValidity("");
}
}
A snippet created using the type="number" instead of type="text" on the input still allows the jQuery functionality to work.
The validation message is HTML5 and not jQuery as you did not provide that code. I did the following:
Changed to type="number"
Added min="100"
Added step="0.01" to handle currency stepping
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Text input (original): <input required id="balance" name="balance" class="number" type="text" /><br />
Number input: <input required id="balance" name="balance" class="number" type="number" min="100" max="99999" step="0.01" /><br />
<input type="submit" />
<small>Enter less than 100 and press 'submit' to see validations.</small>
</form>
you can try to currency validation using regex
<div class="col-sm-3 form-group">
<b>Premium :*</b><br>
<p><input type="text" class="form-control" oninput="this.className = ''" name="premium" id="premium" valideAtt="currency" title="Premium" onblur="defaultValidation(this)"></p>
<span id="er_premium" style="display: block; width:100%; float: left;"></span>
</div>
<script type="text/javascript">
var REG_CURRENCY = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/;
function defaultValidation(src){
var getAttributeValue=src.attributes.valideAtt.value;
if(getAttributeValue=="currency"){
if(!src.value.match(REG_CURRENCY)){
$("#"+src.id).addClass("invalid");
$("#er_"+src.id).html("<span style=\"color:red\">Please Enter Valide currency Value.<\span>");
return false;
}else{
$("#er_"+src.id).html("");
return true;
}
}
}
<script>
I'm trying to update a page by echoing the input of a user in real time through ajax. However, when a user types in something and clicks 'send' there is nothing echoed. But when I preset the input to a random word through html and click 'send' the word is shown. Why is this and how can I update the input value without manually doing so in html?
HTML
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
JQuery
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if(text_value=='') {
alert("Please enter a title first");
}else{
alert(text_value);
}
});
I think what you want is a keyboard event like keyup:
$('#userName').keyup(function() {
var text_value = $(this).val();
if(text_value=='') {
alert("Please enter a title first");
}else{
$("p").html(text_value);
}
});
Also id can only be used once on the page so you need to change one of them:
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="somethingElse" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
<!--for my example-->
<p>Update</p>
FIDDLE
You have a mistake in your HTML as you define id="userName" twice. If you compare strings you always need the === identical operator. Try out this snippet:
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if (text_value === '')
alert("Please enter a title first");
else
alert(text_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Uname" name="typeit" value="" />
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy" />
<input type="button" id="text_value" value="send" />
<div id="test"></div>
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.
I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>