the value parameter is not being passed using jquery? - javascript

<textarea name="inputField" id="inputField" tabindex="1" rows="2" cols="40"onblur="DoBlur(this);" onfocus="DoFocus(this);" ></textarea>
<input class="submitButton inact" name="submit" type="submit" value="update" disabled="disabled" />
<input name="status_id" type="hidden">
the javascript(jquery):
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
console.log("clicked");
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this, "replyto", $("#inputField")[0]);
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the status_id parameter is not being passed:
post.php?reply_to=#muna&status_id=345667
it always give a value of zero, when its meant to give 345667

You have two problems, the first #Guffa mentioned, you need an ID for $("#status_id") to work, like this:
<input id="status_id" name="status_id" type="hidden">
The other is here:
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this, "replyto", $("#inputField")[0]);
Notice you don't have a [0] there, so you're setting .value on the jQuery object, not the element itself. Instead you need this:
insertParamIntoField(this,"status_id",$("#status_id")[0]);
insertParamIntoField(this, "replyto", $("#inputField")[0]);
Or change your method to use .val(), like this:
field.val(kv[1]);
And strip off the [0] calls so they're just
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this, "replyto", $("#inputField"));

You don't have any id on the field, so when you try to set the value using $('#status_id') it won't put the value anywhere.
Add the id to the field:
<input name="status_id" id="status_id" type="hidden">

add value to input
<input name="status_id" id="status_id" value="345667" type="hidden">

Related

get checkbox values from form and add to JSON string using JavaScript

attempting to pull form values and put them into localStorage via JSON string. This code works for everything but checkbox values. How do i also get checkbox values? Please and thanks!
<form id="myForm">
<input type="submit" name="submit" value="submitOrder">
</form>
const userOrder = {};
function getValues(e) {
// turn form elements object into an array
var elements = Array.prototype.slice.call(e.target.elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type !== "submit" && el.type !=="button") {
userOrder[el.name] = el.value;
}
});
// finally save to localStorage
localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
console.log(localStorage.getItem('userOrder'));
use the .checked attribute of a checkbox to tell if it is checked or not
const userOrder = {};
function getValues(e) {
e.preventDefault();
// turn form elements object into an array
//you can also use Array.from(e.target.elements)
var elements = Array.prototype.slice.call(e.target.elements);
console.log(elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type == "checkbox") {
userOrder[el.name] = el.checked;
}
});
console.log(userOrder);
// finally save to localStorage
//localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
//console.log(localStorage.getItem('userOrder'));
<form id="myForm">
<input type="checkbox" name="checkbox-0">
<input type="checkbox" name="checkbox-1">
<input type="checkbox" name="checkbox-2">
<input type="submit" name="submit" value="submitOrder">
</form>
You can use JQuery serialize() function.
Then, you can do something like this:
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() ); // <-----------
console.log( data );
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<input type='checkbox' name='remember-me'>
<br />
<button type='submit'>Try</button>
</form>

How to make sure every input field has greater value than the value of previous input?

How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>

submitting the different value in jquery

I am having the below code to show input field with phone number in certain format. i.e., If phone number starts with 33,55 or 81 I will show it as (33) 1234-5678. If phone number starts with any other numbers, the format will be (123) 456-7890.
Now, the problem is when I submit the form, it is submitted as (33) 1234-5678. But I should submit 3312345678 and display (33) 1234-5678.
Could someone help me, how could i overcome this issue. I didnt use any jquery plugins;
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
You can change the value when the form is submitted, just before it is sent to the server:
$("form").on("submit", function(){
var originalVal = $("#criterion").val();
var newVal = originalVal.replace(/[^\d]/g, '');
$("#criterion").val(newVal);
});
You could have a hidden input that you store the original value of the input before modifying it.
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input type="hidden" id="org" name="org" />
-
$(document).ready(function() {
$("#criterion").change(function () {
var searchBy = $('#smartWirelessSearch').val();
$('#org').val($(this).val());
if(searchBy == 'Mobile'){
$(this).attr("criterion", $(this).val());
var twoDigit = $('#criterion').val().substr(0, 2);
var threeDigit = $('#criterion').val().substr(0, 3);
var remainingDigits = $('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
$('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
$('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
If you need to have the original cleaned value all the time, there are many ways to do that too. One simple solution is to have clean it by your self everytime input changes.
If so, replace $('#org').val($(this).val()); by $('#org').val($(this).val().replace(/[^\d]/g, ''));
This basically replaces everything that is not a digit with an empty string.
There are two possibilities to solve this, the first is to have a second (extra) hidden input like:
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input id="criterion_hidden" name= "criterion_real" type="hidden" size="15" maxlength="60" value="" placeholder="" onkeypress = "submitOnReturn(event);">
And populate it in your jquery:
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
$("#criterion_hidden").val(twoDigit + remainingDigits); //update it here.
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
The other solution is to change the value on the server side (PHP?) by using a replace with a regular expression such as /[^\d]/g.
On submit of the form replace input value of ( ) - with empty string "".
I would suggest two solutions:
1. Toggle Format
With this solution, you either show the formatted value in the input, or the clean digit-only value. So you would take care to show the digit-only value when the form is submitted, but also when the user edits the value (as suggested by #Rune FS):
jQuery(function($) {
function cleanMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Strip all non-digit characters
$("#criterion").val($("#criterion").val().replace(/[^\d]/g, ''));
}
}
function formatMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Apply format after first stripping all non-digit characters
$("#criterion").val($("#criterion").val()
.replace(/[^\d]/g, '')
.replace(/(33|55|81|...)(.*?)(....)$/, '($1) $2-$3'));
}
}
$("#myform").submit(cleanMobile);
$("#criterion").blur(formatMobile).focus(cleanMobile).keypress(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
// Set initial format correctly on page load
formatMobile();
}, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<select id="smartWirelessSearch">
<option value="Mobile">Mobile</option>
</select>
<input id="criterion" name="criterion" type="tel" class="inputboxBg"
size="15" maxlength="60" style="width:85%;" value="" placeholder="">
<input type="submit" value="submit">
</form>
Run the snippet to see how it responds to focus and submit.
Note that the code above also:
Uses a regular expression to format the number;
attaches the keypress handler via code instead of the element's onkeypress attribute;
defines functions for the format manipulations so these can be referenced in blur, focus and submit events;
defines a dummy smartWirelessSearch element so the code is compatible with your form;
gave the form an id myform, which you should replace with yours.
2. Use Hidden Input
If you do not want the input value to visibly change at form submission, you could add a hidden input and give that the digit-only value, like this:
<input id="criterionClean" name="criterionClean" type="hidden">
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15"
maxlength="60" style="width:85%;" value="" placeholder=""
onkeypress="submitOnReturn(event);">
In your Javascript add one line:
if(searchBy == 'Mobile'){
// ... your code ...
// Then pass the digits only in the hidden input
$('#criterionClean').val($(this).val().replace(/[^\d]/g, ''));
}
Now you'll submit both the formatted and the cleaned value. Your server code could then use the clean digit-only value.
If you prefer the clean value to be called #criterion, then swap the names of the two inputs in html and in your code.

get value of non count id

/*get value of non count list,using jquery */
<input type="text" id="loc-51-0" value="ahmed">
<input type="text" id="loc-51-0" value="ahmed">
<input type="text" id="loc-51-1" value="mohamed">
<button onclick="save(51)">
<input type="text" id="loc-52-0" value="alaa">
<input type="text" id="loc-52-1" value="karim">
<button onclick="save(52)">
function save(id){
var x="loc-"+id;
$('input[id^="+x+"]').each(function() {
alert( this.value ); // $(this).val();
});
}
I need to put variable x into loop but it not working
you are having a Syntax Error change this:
$('input[id^="+x+"]').each(function() {
alert( this.value ); // $(this).val();
});
to this:
$('input[id^="'+x+'"]').each(function() {
alert( this.value ); // $(this).val();
});
Try this:
$('input[id^="'+ x +'"]').each(function() {
alert( this.valule );
}) <- you're missing this `)`
also concatenation should be like above.
$('input[id^="+x+"]') should be like $('input[id^="'+ x +'"]')
You need to concatenate your value properly:
$('[id^="'+ x +'"]').each(function() {
alert(this.value);
});
Also, because id is unique, you just need [id^= instead of input[id^=

comparing 50 pairs of input textboxes

If I have 50 pairs of input textboxes, i.e.
<input type="text" id="name_0" /><input type="text" id="name_1" />
<input type="text" id="dept_0" /><input type="text" id="dept_1" />
...
<input type="text" id="age_0" /><input type="text" id="age_1" />
<input type="text" id="weight_0" /><input type="text" id="weight_1" />
i.e 50 variables of these.
When the page loads, I populate each pair with identical data.
What is the best way to check if the _0 is different from the _1?
then returning a message showing which pair has changed.
The comparison should take place once the values have been changed and a button is clicked.
$("input[type=text]").each(function () {
var $this = $(this);
if ( /_0$/.test(this.id) ) {
if ( $this.val() != $this.next("input").val() ) {
$this.css("color", "red"); // or whatever
}
}
});
Tomalak's answer should work, but just in case your inputs are scattered or not necessarily beside each other, something like this should suffice.
$('input:text[id$="_0"]').each(function() {
var new_id = this.id.replace('_0','_1');
if ($(this).val() !== $('input#'+new_id).val()) {
// not the same
}
});
var changed = [];
$("[id$=_0]").each(function() {
var name = this.id.replace("_0", "");
if (this.value != $("#" + name + "_1").val()) {
changed.push(name);
}
});
console.log(changed);

Categories