How to select automatically a text input? - javascript

I want a text input selected (as if I had clicked on) when I click on another element on the page. I can't figure out how to do it?

You are looking for this: pure js way
<img src="http://placehold.it/350x150"
onclick="document.getElementById('target').focus(); return false;">
<input type ="text" id="target"/>
Clicking on image will set focus on the text field.

Assuming that your input field has id #input then solution would be
// Wrapper function needed to ensure that DOM elements have been already rendered.
(function() {
$( '#input' ).focus(); // jQuery
document.getElementByID( 'input' ).focus(); // VanillaJS
})();

Try this. I have not tried it though. It's worth noting that it is based on jquery.
//set focus by default
$("your_input").focus();
//if the focus is lost set it again
$("div").focusout(function(){
$("your_input").focus();
});

Related

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

How to focus a hidden input field

I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it.
I would like it to work like:
User presses "S"
Field appears with "S" typed in it.
Any help would be much appreciated!
http://codepen.io/jeremypbeasley/pen/RNrore
var searchArea = $(".search");
searchArea.hide();
$(document).ready(function() {
$( "body" ).keydown(function() {
searchArea.show();
searchArea.elements['input'].focus();
console.log("worked!");
});
});
What is searchArea.elements['input'] supposed to do ?
Try it like this instead, using jQuery's find method
$( "body" ).on('keydown', function() {
searchArea.show().find('input').focus();
});
PEN
You need to find the input element within the seach area, then call focus() on it:
$(document).ready(function() {
var $searchArea = $(".search").hide();
$("body").keydown(function() {
$searchArea.show();
$searchArea.find('input').focus();
});
});
Updated CodePen
Or just set id to input field (<input autofocus="autofocus" id="hid_inp" >)
and use $("#hid_inp").focus(); instead of searchArea.elements['input'].focus();"

jQuery click event does not update ':last' when i add a new element that should become the new ":last"

So i am having a small issue,
I am working on a small effect on jquery that works this way.
The user is provided with one input button.
as soon as he types something into the input field, a new input is added below it.
Here is the HTML
<div class="container">
<div class="row">
<div class="col-md-4 data">
<input type="text" class="form-control" placehoder="some text"/>
</div>
</div>
<span><i class="fa fa-plus"></i></span>
</div>
Here is the jquery code
$(document).ready(function()
{
var input_button = '<div class="col-md-4 data"><input type="text" class="form-control" placeholder="some text"/></div>';
var last = 'div.data input[type="text"]';
$('div.data input[type="text"]:last').on("keyup",function(e)
{
value = $(this).val().trim();
if(value.length != 0)
{
$('.row').append(input_button);
}
});
});
Therefore, i use the $(div.data input[type="text"]:last) selector and the keyup event.
However, in my own thinking, when i Add a new input button, it should automatically become the ":last" input field. right?
But this is not the case. The last input field is, according to how the code is working, the first input field that originally existed?
Basically the first original input button is considered the "last" button even when more are added by the keyup event.
So my question is, how do i make the newly added input field (added using jquery) the last input field on the next keyup event?
The problem is that you bind to elements that are searched only once, not to a dynamic selector.
You should use
$('div.data').on("keyup", 'input[type="text"]:last', function(e)
so that the 'input[type="text"]:last' selector is checked each time there's a keyup event in a descendant of an element of $('div.data').
As your question isn't clear, in case you also dynamically add the div.data element, then you should do
$('.container').on("keyup", 'div.data input[type="text"]:last', function(e)
To read more about event delegation in jQuery, you can check this page.
When you dynamically create an element you have to select a parent element that is not being dynamically created then use the on function to trigger a function on an event.
So in your case you have to select a parent that is not being dynamically created which is .row and use the on function as follows:
$('.row').on("keyup", 'input[type="text"]:last', function (e)
http://jsfiddle.net/55SNt/
As the content are dynamically added on the fly , the event handler defined in your question points to the static field generated on page load. Instead you should do :
$(document).on("keyup", 'div.data input[type="text"]:last', function(e)
{
value = $(this).val().trim();
if(value.length != 0)
{
$('.row').append(input_button);
}
});
here is the example.
See More about Event Delegation.
To understand what's going on, you have to consider what jQuery is doing:
//Your code:
$('div.data input[type="text"]:last').on("keyup", function(e) {
//...
});
It looks like one thing is happening there, but there are actually two:
First you wrap the last element that matches div.data input[type="text"] in a jQuery object,
Then you add a handler to it.
Once $('div.data input[type="text"]:last') runs, the element it contains isn't going to change. It's already been found. The event handler is operating on that specific element, not the position it occupies.
To fix this, you have to tell jQuery to bind the handler dynamically every time the event fires. Fortunately, the on method is clever about that, and gives you the option to do it differently:
$(document).on("keyup", 'div.data input[type="text"]:last', function(e) {
//...
});
This will search the entire document for 'div.data input[type="text"]:last' before firing the event handler.

Inner HTML with input values

have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):
http://jsfiddle.net/F7urT/2/
jQuery:
jQuery(document).ready(function($) {
$('.send').click(function() {
alert( $('.content').html() );
return false;
});
});​
html:
<div class="content">
<input type="text" name="input" value="Old Value" />
<input type="button" class="send" value="Send" />
</div>​
If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?
The new value is stored as a property not an attribute, the value can be obtained by inputelement.value, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.
For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option
http://jsfiddle.net/mowglisanu/F7urT/5/
this solution is better. works for more inputs.
$('input[type=text]').attr('value', function (i, val) { return val; });
$('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
$('textarea').html(function () { return this.value; });
$('select').find(':selected').attr('selected', 'selected');
You can't get it with .innerHTML (.html()). Writing into an element doesn't modify the html markup, nor will it change the value attribute in actual markup.
You can only access the current content by directly asking the element for its .value - value. Using jQuery, you can do that via .val() too.
$('#input_id').attr('value',$('#input_id').val()); will put the value into the html
DanCZ & Musa solutions works pretty good, but I had trouble with the textarea.
I have to implement this in a Typescript project and the only way I've found to make the textarea show the value is this :
textarea.innerHTML = textarea.value;

how to set the selected option of a select element without triggering a change event?

I'm currently using this on a select:
var sortNo = $('select[name=anzahl_eintraegeSEL]');
sortNo
// set selected based on hidden input default value
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')
.attr('selected', 'selected').attr('set',true)
// set up change listener
.on('change', function(){
// do sth
});
I want to set the default option to selected without triggering an initial change event.
How can I get this to work? The above seems to trigger a change event right away.
Thanks for help!
You can try:
sortNo
.on('change', function(){
// do sth
})
.val($('input[name=anzahl_eintraege]').val()); // set the default value get from hidden field
DEMO
for once: In this line:
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')
You are missing the closing '"'. Should be:
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +'"]')
Next your .on() is executed while jQuery has your tag on top... I guess you want the change of the , not on the .
And you don't need to find the option tag yourself, jQuery can do that for you, using sortNo.val().
I believe that is what you want?: http://jsfiddle.net/KadrG/

Categories

Resources