Showing the incorrect textbox title - javascript

The code below is made to detect the name of the input method user focus in , the problem is it alerts the same name for all textboxes.
var huntedTextBox;
//focus in any textfield to get its name into the vairable.
$("input").focus(function() {
huntedTextBox = $("input").attr('name');
alert(huntedTextBox);
});
Here is a Fiddle for the code.
Thanks.

Just doing a search for $('input') will return all <input>s in the document. Then, doing .attr() will get the attribute for the first.
To get the attribute of the <input> that was clicked, use $(this).attr('name');

You need to use this for selecting that particular textbox that's focused on...
Here's a snippet:
var huntedTextBox;
//focus in any textfield to get its name into the vairable.
$("input").focus(function() {
huntedTextBox = $(this).attr('name');
alert(huntedTextBox);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textBox" />
<input type="text" name="Bader" />

huntedTextBox = $(this).attr('name');

Related

Linking form and button to javascript command

I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO

Getting data from input using JavaScript

I am trying to get a value out of a <input type='num'> with JavaScript I am using the following code:
Choose a number between 1 and 5 <input type='num' name="input">
<button id="btn">Click me!</button>
<script>
var input;
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value input has
</script>
This should get a value but I just get a null what am I doing wrong?
You have not defined your id. Also I guess your input type should be number.
<input type='number' name="input" id="num">
^^^^^^^^^^^^ ^^^^^^^^
And to alert its value you need to use
alert(input.value) //.value is used to get value of input
There are more than one problems with your code
1) You have to close the bracket of your function
it should be
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value is outputted
}
2)
input = document.getElementById('num');
The getElementById() method returns the element that has the ID
attribute with the specified value.
so ID attribute is essential here and in your code there is no ID attribute defined so you have to defined it first
like
<input type='number' id="num" name="input">
3) document.getElementById('num'); does not return the value of input field
it returns object
so if you want value then use the following code
document.getElementById('num').value;
4) your input type="number"
for the desired output you can use following code
Choose a number between 1 and 5 <input type='number' name="input" id="myid">
<button id="btn">Click me!</button>
JS
var myButton = document.getElementById("btn");
myButton.onclick = function()
{
alert(document.getElementById("myid").value); //where does id come from?
}
The above method is pure JS if you need jquery method you can refer below
$( "#btn" ).click(function() {
var input=$("#myid").val();
alert(input)
});
getElementById() works on elements with id attribute. So, as you have not put id attribute in your input type, it is not able to find the element with id=num.
Just add id="num" in your input element and then you are good to go.

Form HTML not getting updated.

Here's something weird
<form>
<input type="text" id="test" value="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert($(this).html());
});
</script>
http://jsfiddle.net/F6XvW/
I change the value of the input field, then click submit to get the HTML, but the value is not updated inside the HTML? What's up with that? How to get the updated HTML?
What the user inputs is never changing the HTML. It's a form value which will be sent as a parameter to the server.
See here: your jsfiddle updated:
<form>
<input type="text" id="test" placeholder="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert('inputted value = ' + $(this).find('input[type=text]').val());
});
</script>
If you really want to update the DOM, you have to manually set it: http://jsfiddle.net/F6XvW/3/
JS
$('form').submit(function(ev){
ev.preventDefault();
$('#test').attr("value", $('#test').val());
alert('changed input value to: ' + $(this).find('input[type=text]').val());
});
Changing the input of a value does not change the Document Object Model (DOM).
SOLUTION
$('form').submit(function(ev) {
ev.preventDefault();
var newinputval = $(this).find('input[type=text]').val();
var newhtml = $(this).html();
newhtml = newhtml.replace("abc", newinputval);
alert(newhtml);
});
As you see I first receive the new input value, then I get the HTML and replace the DOM's value with the current input value. Now it does exactly the thing that you want.
JSFiddle demo
The value attribute shows the default value, not the current value (which is available in the DOM property of the same name.
If you want to get the current value, then you would have to loop over all the form controls and get their values from the DOM.
You are reading out the initial HTML - changing value on the page will not change in this HTML. Try:
$('form').submit(function(ev){
ev.preventDefault();
alert($('#test').val());
});
...to get the value of the input.
If you want to get value of any input use
$('form').submit(function(ev){
ev.preventDefault();
alert($("#test").val());
});
$('input').val();
in forms you can use .serialize();

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

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