input string in javascript - javascript

Short question
QUESTION
How can I access the string value "2013-10-20" from the input in HTML to show it in JavaScript?
HTML
<input name="DateStart" class="inputPanel" type="text" size="20" maxlength="20" value="2013-10-20">
JAVASCRIPT
<script javascript="javascript" type="text/javascript">
alert("Value: " + ???)
</script>
Thanks!

Assuming you have one input with the name DateStart(use id's):
alert("Value: " + document.getElementsByName('DateStart')[0].value);

If the input is in a form, and there is only one form in the document, you can access it like:
alert(document.forms[0].DateStart.value);
If the form has a name you can use:
alert(document.forms['formName'].DateStart.value);
or if you like being long–winded:
alert(document.forms['formName'].elements['DateStart'].value);
or if the name is also a valid identifier (i.e. a name you could also use as a variable name)
alert(document.forms.formName.DateStart.value);
or even:
alert(document.formName.DateStart.value);
Or an ID:
alert(document.getElementById('formId').DateStart.value);
Or using the querySelector interface:
alert(document.querySelector('input[name="DateStart"]').value);
Lots of ways to skin that cat.

From the current code you can use getElementsByName
var dateStart = document.getElementsByName('DateStart')[0];
alert("Value: " + dateStart.value);
But it's advisable and a best practice to add Id attribute on DOM element and using getElementById in JavaScript to retrieve DOM element. (take a look at name vs id)
HTML
<input id="DateStart" name="DateStart" class="inputPanel" type="text" size="20" maxlength="20" value="2013-10-20">
JavaScript
var dateStart = document.getElementById('DateStart');
alert("Value: " + dateStart.value);

You can say like bellow
alert(document.getElementsByClassName('inputPanel')[0].value);
if this is first element which has class inputPanel.

Related

How to use jquery to add numbers to input ID name

I am using a wordpress plugin that is generating a input field with a given ID name - fieldname15_6
Im using the code in a loop though so for each post it is creating that input field with the same ID name. Of course this is a problem. I have about 10 inputs with the same ID name and I believe it's causing issues with the display. The font sizes and spacing seems a little random regardless of my CSS rules.
Any how, I need a way to automatically add numbers 1+ to any of the created inputs with that ID name. I tried using the following code but it does nothing --
$("input[id^='fieldname15_6']").attr('id', function (i) {
return "fieldname15_6" + ++i;
});
What am I doing wrong?
Thanks.
var i = 1;
$("input#fieldname15_6").each(function(){
$(this).attr('id', function(i) {
return "fieldname15_6" + ++i;
});
});
This will help you.....
$("input[id^='fieldname15_6']").each(function(i){
$(this).attr('id', $(this).attr('id') + i);
});
Try this:
var $files = $('body').find("input").attr("id","fieldname15_6");
$files.each(function(index)
{
newIndex = $(this).attr("id") + index;
$(this).attr("class", newIndex );
});
The simple answer is Don't. You should use classes for this type of thing, that's what they are for. Then you can use various methods to target and work with the individual elements like .eq()
$('#result').html($('.fieldname15_6').eq(2).val()); // eq is 0 based array syntax so 2 will be the 3rd element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="fieldname15_6" value="first value">
<input type="text" class="fieldname15_6" value="second value">
<input type="text" class="fieldname15_6" value="third value">
<br>
<br>
<br>
<br>
<div id="result"></div>

How to get value from form field and concatenate with url in Jquery

I am using jquery for the first time today and need help with this problem. For the all the pros out there, this issue might sound dumb but I am struggling.
I have a form field in a HTML page, and want to get value from the form field and concatenate with a url.
<form id="form-container" class="form-container">
<label for="street">Street: </label><input type="text" id="street" value="">
<label for="city">City: </label><input type="text" id="city" value="">
<button id="submit-btn">Submit</button>
</form>
This is tag where I am want to add the values of street and city.
<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=White House, Washington DC&key=API_KEY">
</body>
Basically the location field in this src will come from the form field. so something like this:
<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + $('#street').val() + "," + $('#city').val()&key=API_KEY">
</body>
But unfortunately this is not working and need some pointers to resolve this.
UPDATE : I am trying this method to achieve this but not working
$body.append('<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + $('#street').val() + " " + $('#city').val() + "&key=ABC">'
You can do something like this:
var url = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location={street},{city}&key=API_KEY";
$("#submit-btn").on('click', function() {
var street = $('#street').val();
var city = $('#city').val();
var finalURL = url.replace('{street}', street).replace('{city}', city);
$('.bgimg').attr('src',finalURL);
});
Note that you shouldn't have src attribute set in the HTML, else browser will fire a request to invalid source.
Also make sure to validate the user inputs and that you've jQuery.
If You need to do it using jQuery then set the value of 'src' property of img tag like this:
$('.bgimg').prop('src', '"https://maps.googleapis.com/maps/api/streetview?size=600x300&location=' + $('#street').val() + ',' + $('#city').val() + '&key=API_KEY')
You should modify the src of your image on form submit.
Possible duplicate of this thread (you will find a detailed answer there): Changing the image source using jQuery
So something like:
function setSrc(){
$('.bgimg').prop('src','https://maps.googleapis.com/maps/api/streetview?size=600x300&location=' + $('#street').val() + ',' + $('#city').val() + '&key=API_KEY');
}
<form id="form-container" class="form-container" onSubmit="setSrc();">

Accessing Input element through input name in javascript

I want to access the following code using java script. Can anyone help me please? I'm a beginner to JavaScript.
<input type="text" name="username" />
I wish to access the element from its name property. An alert box needs to be shown if the length of element value is less than 6.
Use getElementsByName() method,
document.getElementsByName('username')
getElementsByName() returns an array of elements.
The getElementsByName() method returns a collection of all elements in the document with the specified name
var x = document.getElementsByName("username")[0].tagName;
Its better you can use id instead of name if it is unique.
<input type="text" id="username" />
var x=document.getElementById("username");
Try using document.getElementById(), need to specify unique id
var usrtxt = document.getElementById('usrtxt');
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" id='usrtxt' value='admin' />
Try using document.getElementsByTagName()
var inputArray = document.getElementsByTagName('input');//gives array
var usrtxt = inputArray[0];//get first element
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" value='admin' />
Probably the input is in a form like:
<form ...>
<input name="username">
...
</form>
and probably you want to validate it when the form is submitted, so in that case you likely have a listener on the form like:
<form onsubmit="return validate(this)" ...>
and in the validate function:
function validate(form) {
// get input as form.username
if (form.username.value.length < 6) {
alert('Username must be 6 or more characters long');
// Prevent form submission
return false;
}
}
You may want to be more sophisticated with the UI (your users will appreciate it), but the above shows the basics.
If you wish to identify particular element using Name then use getElementsByName function
Javascript:
var x = document.getElementsByName('username');
If you consider to use the Jquery then please use following code.
Jquery:
$('[name="username"]');
Learn more about Jquery Selectors
Update:
var x = document.getElementsByName('username'); // X is an array here as getElementsByName returns collection i.e. Array
var val = x[0];//get first element
if(val.value.length < 6) // Check if its value greater than 6
{
alert('boom !!');
}
}

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

Using Javascript to get value from input

my html code:
<li id='category-10'>
<label class="selectit">
<input value="10" type="checkbox" name="post_category[]" id="in-category-10" /> Developmental
</label>
</li>
my javascript code:
function onCategoryClick() {
$(".selectit").click(function(e){
var categoryValue = $(e.target).text();
alert("The value is " + categoryValue);
});
}
This returns me the string "The value is Developmental" but what I want is "The value is 10"
I'm new to Javascript, how would I go about targeting the value field in the input, instead of the text?
I've also tried
var categoryValue = $(e.target > input).value;
But this doesn't return anything.
Instead of
$(e.target).text();
try
$(this).find('#in-category-10').val();
Here e.target corresponds to the label . And it has text 'Developmental' and also a nested input element.
So you need to use find to access it. (If there is no id)
But ID is supposed to be unique on the page. So to access the element you can directly used the id selector
var categoryValue = $('#in-category-10').val();
And remember that input has no text property. Need to use the val method

Categories

Resources