How to get update all hidden fields with same name? - javascript

I have multiple hidden field with same name on html page like below
<input type="hidden" name="customerID" value="aa190809" />
I need to update values of all hidden field with same name i.e. customerID
I know how to do it(through Jquery) if html page contains single hidden field with customerID like below but not sure if there are multiple hidden field with same name
if(updatedCsrf !== null) {
var customerIDHidden = $("input[name='customerID']");
if(customerIDHidden !== null) {
customerID.val("some_value");
}
}

You can do something like this:
$("input[name=customerID]").each(function(){
this.value ="new value"
})
this will reference each DOM element. You can parse it again to jQuery DOM element by replacing this.value to $(this).val("new value") but since you only need to change the value its better with javascript vanilla

You can do that with pure JS,
var x = document.getElementsByName("customerID");
for(var i=0; i < x.length;i++){
x[i].value='new value';
}

Use jQuery each function
$("input[name='customerID']").each(function(){
$(this).val("some-value");
});

Related

How to hide certain characters within an html input list?

I have an html input list, with an associated datalist, defined as follows:
<input list="mylist" id="my-input" name="friend-name"
placeholder="Begin typing friend's name here..."
required class="form-control">
The list itself (and the associated datalist) is working fine. However, each of my entries are of the form: "String [numeric_id]"
What I am wondering is if there is any way that I can somehow hide
the [numeric_id] part before the form is submitted.
I have looked at the pattern attribute, but that seems to limit the
actual data allowed in the input, which isn't what I want - I just
want the part between square brackets [] to be hidden, but still
submitted to the form.
It would be ok to move it to another input of type=hidden as well.
Is there any possible way to do that?
#isherwood, here is my form tag:
<form action="/chat_forwarding/modal_edit_msg.php" id="fwd-form" method="POST" class="form-inline" style="display: block;">
If you're not using any framework that support binding, you should listen to input events and update a hidden input based on that.
This is a function that may give you the idea:
let realInput = document.getElementById('real-input');
let userInput = document.getElementById('user-input');
userInput.addEventListener('input', function(value) {
const inputValue = value.target.value;
realInput.value = inputValue; // update the hidden input
const userInputResult = inputValue.match(/\[[^\[]*\]/); // the regex for [numberic_id]
if (userInputResult) {
userInput.value = inputValue.substring(0, [userInputResult.index - 1]); // -1 is to remove the space between the 'string' and the '[numeric_id]'
}
});
I should have mentioned that my input is also using Awesomplete (and jQuery). For this reason, binding normal events like keyup did not work (the event would fire whenever a user typed a key). I was able to achieve the functionality I wanted with the awesomplete-selectcomplete event as follows (this will add a hidden input element with value of the id from a string of the form "String [id]"):
$("#my-input").on('awesomplete-selectcomplete',function(){
var fullStr = this.value;
//alert(fullStr);
var regex = /\[[0-9]+\]/g;
var match = regex.exec(fullStr);
//alert(match[0]);
if (match != null) // match found for [id]
{
var fullName = fullStr.substr(0,fullStr.lastIndexOf("[")-1);
var x = match[0];
var id = x.substr(1, x.lastIndexOf("]")-1);
//alert(id);
$('#fwd-form').prepend('<input type="hidden" name="h_uid" value="' + id + '">');
$('#my-input').val(fullName);
}
});

Set Default Value for hidden field

I have a hidden field where i save a value when button is clicked. But on page load there is no value assigned to it. I need to know how to set default value of hidden field.
I am saving a string in hidden field when button is clicked and then access it in a JS function. But on page load the JS function return Undefined value error as the value of hidden field is not set on page load.
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom != "")
{
// logic here
}
}
You can simply try with this
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom) {
// logic here
}
}
So if(nom) will return true only when it has non-blank value. It'll return false if it is "" or undefined
Now the next thing, you need to make sure about the Id of the element. If you are using the asp.net hidden field with runat="server" then Id would be different than what are you expecting. So to make sure that Id remains same as you've given in asp.net markup, use ClientIdMode="Static"
you can also do this:
if (nom != "" || nom != undefined) {
//Your Logic
}
try to use this
if (nom !== "" && nom !== undefined)
so, your code should be rewritten as below
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom !== "" && nom !== undefined)
{
// logic here
}
}
Here for only text,password fields in html only you can give a default value attribute .But in the case of html
<input type="hidden" value="">
element the value would not be assigned by default.
If you want to use a hidden field with a default value use a text field with the property of display:none like
<input type="text" style="display:none" value="Default">
Or else if you are determined to use the hidden element only then you can go for a javascript based check solution like
var nom = document.getElementById('hdNomValue').Value;
if (nom != "" || nom != undefined)
{
}
what are you using jquery or javascript, if u are using jquery you may try to use
var nom = $('#hdNomValue').val();

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

Place div.innerHTML as a hidden form value

I have a long page with identical section I am attempting to combine into one that has:
TITLE
description
form
I have working mouseovers that change the title and description, but need a solution to change the value of a hidden form input to the new titles when changed.
HOW do I get the hidden form value to change onmouseover to equal current TITLE.value?
Milestones
PHP
function changeContent(id, msg) {
var el = document.getElementById(id);
if (id) {
el.innerHTML = msg;
}
}
FORM
<input type="hidden" value="" name="category" />
Is this what you're looking for?
document.getElementById('hiddenInputId').value = msg;
Your hidden element doesn't have an Id, so you can use following:
var elems = document.getElementsByName('category');
elems[0].value = <<new value>>
getElementsByName always returns an array so you have to pickup first element and set its value.
Cheers !!

jQuery access input hidden value

How can I access <input type="hidden"> tag's value attribute using jQuery?
You can access hidden fields' values with val(), just like you can do on any other input element:
<input type="hidden" id="foo" name="zyx" value="bar" />
alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());
Those all mean the same thing in this example.
The most efficient way is by ID.
$("#foo").val(); //by id
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
https://developers.google.com/speed/docs/best-practices/rendering?hl=it#UseEfficientCSSSelectors
There's a jQuery selector for that:
// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );
// Filter those which have a specific type
hidden_fields.attr( 'text' );
Will give you all hidden input fields and filter by those with a specific type="".
To get value, use:
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
var valueOfHidFiled=$(this).val();
alert(valueOfHidFiled);
}
});
or:
var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);
To set value, use:
$('input[type=hidden]').attr('value',newValue);
There is nothing special about <input type="hidden">:
$('input[type="hidden"]').val()
If you want to select an individual hidden field, you can select it through the different selectors of jQuery :
<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/>
$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class
If you have an asp.net HiddenField you need to:
To access HiddenField Value:
$('#<%=HF.ClientID%>').val() // HF = your hiddenfield ID
To set HiddenFieldValue
$('#<%=HF.ClientID%>').val('some value') // HF = your hiddenfield ID
Watch out if you want to retrieve a boolean value from a hidden field!
For example:
<input type="hidden" id="SomeBoolean" value="False"/>
(An input like this will be rendered by ASP MVC if you use #Html.HiddenFor(m => m.SomeBoolean).)
Then the following will return a string 'False', not a JS boolean!
var notABool = $('#SomeBoolean').val();
If you want to use the boolean for some logic, use the following instead:
var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }
Most universal way is to take value by name. It doesn't matter if its input or select form element type.
var value = $('[name="foo"]');

Categories

Resources