Cant get value of input - javascript

I try to get input value of my form. I already try many solutions but still no results. Here is form input:
<input class="form-control" id="account_ya_price_list_url shop_key_input" name="account[ya_price_list_url]" type="text" style="/* margin-right: 20px; */">
Js:
console.log($('#shop_key_input').html());
console.log($('#shop_key_input').val());
console.log($('#shop_key_input').value);
var div = document.getElementById('shop_key_input');
var div2 = document.getElementsByName('account[ya_price_list_url]').first;
console.log(div2.innerHTML );
console.log(div.innerHTML );
console.log(div2.value );
console.log(div.value );
All of this or undefined or null. What I am doing wrong?

The value of the id attribute needs to be an id not a space separated list of ids (it does not work like the class attribute).
id="account_ya_price_list_url shop_key_input"
should be
id="shop_key_input"
then #shop_key_input will match it.

Only one ID is allowed per element.
So try using just #shop_key_input and using either
document.getElementById('shop_key_input'); or $('#shop_key_input')

use class to get the value of textbox
$('.form-control').val();

Related

Can the <button> 'value' attribute be a number?

Example:
<button type="button" value="5">5</button>
What I'm trying to do is create a javascript calculator. When the button is pushed, I would like to be able to display that value. Currently, I cannot seem to figure out how to retrieve the value and am unsure if it's valid to use a number.
According to W3Schools
value: text
This means "value" attribute always receives a text (string).
You can always parse the number if in need.
i.e.
// having myButtonValue as the value from button
var number = +myButtonValue
In this case it would be most appropriate to use the data attribute .. Like so:
<button type="button" data-value="5">5</button>
Then you can retrieve it simply using :
var el = document.querySelector('your_button');
console.log(el.getAttribute('data-value'));
NOTE That I am using querySelector as a generic term .. You could give it a class, name or ID -- And retrieve it IE getElementById()
Try using an input instead:
<input id="b5" type="button" value="5" />
you can then parse the value into a number:
const value = document.getElementById("b5").value;
Any component can have any attribute, but the button for selecting integers values may not be the most HTML semantically correct.

How to get input value with no id using JavaScript?

I have an editable DataTabe and when edit mode, the generated html is exactly as shown below:
<td><form><input autocomplete="off" name="value" ></form></td>
There is s TextBox as input and I need t get the value of this input. However, I cannot give id as there is no configuration of DataTable and I decided to get the value using Javaascipt. I have tried many different methods like closest() as shown below, but cannot get the value. Is it possible to grab it?
var $row = $(this).closest("tr");
$tds = $row.find("td");
You might use document.querySelector:
var input = document.querySelector('[name="value"]`);
Or, using jQuery, you could also use the same selector:
var input = $('[name="value"]');
var currentInput=null;
$("input").focus(function(e)
{
currentInput=e.target or this;//here you can get currently editing textfeild or may be $(this) if this is wrong
});
then you can get currentInput.value()
I see you are using jQuery; you can target the name attribute directly and to get a value of the input use .val(), like so:
$("input[name='value']").val();

How to get value of another input field using javascript

How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck

Styling input field of dynamic ID using getElementById

I have some input fields that has its id's number changes dynamically.
For example, the below code shows an input field that has "id="field14". The word (field) in the id does not change, but the (number) is changing dynamically. So it may be field14, field13, or field20, etc, and there is no limit for numbers.
<input type="text" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
I'm using the following code to style the input field:
document.getElementById("field14").style.height = "24px";
Note, the application's PHP code is encoded & I'm editing in smarty template.
The input code in the template is like this: {$field.input} So when I inspect element on the live page it shows the above code of the input with the dynamic number of the id.
I want a way that allow me to style any input field of the page that starts with the word (field) and ends with a dynamic (number). Any suggestions please?
For a pure CSS approach, I would check the name instead, so you should only look for input elements whose attribute starts with field[ and ends with a closing bracket ].
e.g.
input[name^="field["][name$="]"] {
...
}
From the code you posted you can reasonably suppose that the name of all the elements containing a numeric index inside brackets [] are also the same elements with that dynamic index as a part of your id.
otherwise you may write a more complex set of selectors looking for an id starting with field and ending with a digit [0..9]
e.g.
input[id^="field"][id$="0"],
input[id^="field"][id$="1"],
input[id^="field"][id$="2"],
input[id^="field"][id$="3"],
input[id^="field"][id$="4"],
input[id^="field"][id$="5"],
input[id^="field"][id$="6"],
input[id^="field"][id$="7"],
input[id^="field"][id$="8"],
input[id^="field"][id$="9"] {
...
}
or even combine both the methods
input[name^="field["][name$="]"][id$="0"],
input[name^="field["][name$="]"][id$="1"],
...
input[name^="field["][name$="]"][id$="9"] {
...
}
You can use an attribute selector:
input[id^=field] {
/* Styles */
}
It will match all input elements whose id attribute begins with "field". Using some separator between "field" and the number may be better to prevent matching things like "fieldone".
input[id^=field] {
background: red;
}
<input id="field1" />
<input id="field2" />
<input id="field3" />
<input id="field15" />
<input id="field99" />
i strongly recommand using a class attribute:
HTML
<input type="text" class="fields" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
CSS
.fields {
/*style*/
}
I want a way that allow me to style any input field of the page that
starts with the word (field) and ends with a dynamic (number). Any
suggestions please?
This is a very specific question that wants us to key on the fact that the id starts with "field" and ends in a dynamic number. IMHO this solution answers your question exactly as asked using only CSS, plus it doesn't require you to change your HTML or add a class attribute (although this would be much better).
This CSS code will find any <input> tag that has an id starting with "field" and ending in a number. It will also exclude those that start with "field" but do not end in a number.
input[id^='field'][id$='0'],input[id^='field'][id$='1'],input[id^='field'][id$='2'],input[id^='field'][id$='3'],input[id^='field'][id$='4'],input[id^='field'][id$='5'],input[id^='field'][id$='6'],input[id^='field'][id$='7'],input[id^='field'][id$='8'],input[id^='field'][id$='9']
{
// styling code
}
Demo code: http://jsfiddle.net/Drakes/7wpnL/671/
If you need JS approach:
http://codepen.io/knitevision1/pen/LEaXxW
var num = 2;
document.getElementById("input" + num).style.backgroundColor = "blue";
If I get you right, you need all your new input look somewhat unique or something.
You can think of getting a number of the currently presenting inputs, then get the last of them, then attach your style based on what you want it to look like.
Using jquery:
var inputs = [];
function getFields(){
$('input').each(function() {
if($(this).attr('id').substring(0,5)=='field'){
inputs.push($(this));
}
});
}
you can modify each input inside the "each" loop, or you can use the "inputs" variable.
Demo: http://jsbin.com/kubaku/1/edit?html,js,output
JS
var inputs = document.getElementsByTagName('input');
var ID = 'field';
var i;
for(i = 0; i < inputs.length; i++) {
var input = inputs[i];
var regex = new RegExp("^" + ID);
if(regex.test(input.id)) {
input.style.border = '1px solid #c00';
}
}

Change all id's in HTMLDivElement using jQuery

I am using jQuery to dynamically append a Django formset.
I am using a link to add another form identical to the one above it. I do this with the following code:
var row = $("."+class_name).first().clone(true);
row.find('input').val('');
$(row).removeAttr('id').hide().insertAfter("."+class_name).last().slideDown(300);
Every label in row[0] (which is a HTMLDivElement) is id_cur-0-... And everytime I use this jQuery function to add a div, I need every id to increment the number after cur. So the first time I click it every item would have id_cur-1... And the next time they would have id_cur-2... And so on.
If I could treat the HTMLDivElement like a string I could use regex to basically find every occurrence of "cur-\d". How would I do this? Or is there a better way (because this kind of seems like a hack).
Here's what my HTML looks like:
<div class="item1">
<label style="display:inline-block;" for="id_cur-0-cur_child_name">
Name:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_name" name="cur-0-cur_child_name" type="text" />
<label style="display:inline-block;" for="id_cur-0-cur_child_sex">
Sex:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_sex" name="cur-0-cur_child_sex" type="text" placeholder="[M / F]" />
<label style="display:inline-block;" for="id_cur-0-cur_child_dob">
DOB:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_dob" name="cur-0-cur_child_dob" type="text" placeholder="e.g. 12/25/2014" />
</div>
Would this do?
var last_id = $("."+class_name).last().attr("id").split("-")[1];
fiddle
UPDATE
Hi there, the ev.preventDefault only serves the purpose of preventing the default behaviour of the anchor. It stops the default action of an element from happening.
I saw your html and here you have a new fiddle
Javascript code (commented):
$("#clone").click(function (ev) {
ev.preventDefault();
var row = $(".item1").last().clone(true);// Last item1
var last_id = $(row).find("input:first").attr("id");// Grab first input id (it contains the important part: the number)
row.find('input').val('');
$.each(row.find('input'), function (index, item) {// Change id of all inputs inside the cloned element.
var id = (+(last_id.split("-")[1])+1), // Grab the number and increase it.
new_id = $(item).attr("id").replace("id_cur-" + last_id.split("-")[1], "id_cur-" + id);// Replace ids with the new number.
$(item).attr("id",new_id);// Asign the new id to the inputs. You'll have to do more or less the same to the labels if you like.
});
$(row).removeAttr('id').hide().insertAfter(".item1:last").slideDown(300);// Insert after the last item1 element. Otherwise it'll insert after all elements with class .item1
});
Hope it helps.
Kind regards.
Instead, you can use id_cur as the class name, and the specific id with the id attribute as such:
var last_row = $("."+class_name+":last");
var new_row = last_row.clone(true);
new_row.attr('id', new_row.attr('id')+1);
new_row.find('input').val('');
new_row.removeAttr('id').hide().insertAfter(last_row)
new_row.slideDown(300);
You simply have to increment the id attribute with the last one + 1.
Just for clarification: You were using first() to select the first matched element and clone it in var row = $("."+class_name).first().clone(true);, but in this case, if we want to increment the id accordingly, we must clone the latest element added.
Hope this helps !
Cheers,
I could use regex to basically find every occurrence of "cur-\d".
Use the JQuery regex selector to find all id or whatever attr.
Select all the label tag element in which the for attribute start with id-cur-
$("label[#for^=id-cur-]")
Select all input tag element with id beginning with id-cur-
$("input[#id^=id-cur-]")
Hope this may help to select the dom element with regex.

Categories

Resources