How do I change the value of an input element? - javascript

is it possible to "override/overwrite" an input element fixed value using javascript and/or jquery?
i.e. if i have an input element like this:
<div id="myDiv">
<input type="text" name="inputs" value="someValue" />
</div>
is it possible to make a jquery object of that element and then change its value to something else then rewrite the jquery object to the dom??
I'm trying but obviously I haven't got good results!
I've been trying something like this:
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);

If you just want to manipulate the value of the input element, use the first line of your code. However it will change the value of every input element on the page, so be more specific using the name or the id of the element.
$('input[name=inputs]').val("someOtherDynamicValue");
Or if the element had an id
$('#someId').val('some Value');
Check out jQuery's selectors (http://api.jquery.com/category/selectors/) to see how to get whatever element you need to manipulate with jQuery.

You can directly access the value via the $.val() method:
$("[name='inputs']").val("Foo"); // sets value to foo
Without needing to re-insert it into the DOM. Note the specificity of my selector [name='inputs'] which is necessary to modify only one input element on the page. If you use your selector input, it will modify all input elements on the page.
Online Demo: http://jsbin.com/imuzo3/edit

//Changes on the load of form
$(document).ready(function(){
$('#yourTxtBoxID').val('newvalue');
});
//Changes on clicking a button
$(document).ready(function(){
$('#somebuttonID').click(function(){
$('#yourTxtBoxID').val('newvalue');
});
});

Related

How to click a HTML element with javascript

I need to use javascript in order to click an element from element collection. As seen the code has C# but also as seen I need to use a javascript command as I do.
I am looking for this javascript code.
This element doesn't have an ID or name. Otherwise, I could have used the ID but that doesn't work in this case. How would it be possible to use the iterating elements in order to click with javascript"?
The problems are:
1. First I need to click this input/textbox to make it possible to edit.
2. Now when the input is editable. I need to put a number value to the textbox.
foreach (Gecko.GeckoHtmlElement elements in wb1.Document.GetElementsByTagName("input"))
{
if (elements != null)
{
if (elements.OuterHtml.Contains("thisstring"))
{
//This element doesn't have an ID or name. "how to use elements in order to click with javascript"?
//1. First I need to click this input/textbox to make it possilbe to edit
//2. Now when the input is editable. I need to put a value to the textbox.
webbrowser.Navigate("javascript:void(document.getElementById('someID').click())");
}
}
}
The HTML surrounding the element I want to click is below. You can see the input there:
<td class="date-cell" cm-inventory-grid-copy-action-focus data-header-date-index="0" data-cm-inventory-grid-copy-action-focus-type='availability' ng-class="{ 'zero': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availability <= 0, weekend: headerDates[0].weekend, 'dirty': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availabilityChanged, 'copy-focused': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].copyFocused && roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].copyFocusType == 'availability' }" ng-form="cellForm">
<input name="rtd-availability" type="number" onclick="this.select()" ng-model="roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availability" ng-change="handleRoomTypeDateChange(roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate])" pattern="\d+" ng-disabled="::!allowAvailabilityEdit" required sm-no-scroll cm-inventory-grid-date-cell-validator/>
</td>
To get html element in javascript you can use "document.querySelector('input')" or if there are many input elements you can use "document.querySelectorAll('input')".
querySelector returns HTML node element and querySelectorAll returns array of elements.
By using document.qerySelector you can identify the correct input quite easily since you can use attributes and the html structure as criteria.
//select an input that is a child of a td with class date-cell who's name is rtd-availability
let input = document.querySelector('td.date-cell > input[name=rtd-availability]')
//no need to call .click(), you can use .select() directly
input.select();
input.value = 42;
javascript:(() => {let in = document.querySelector('td.date-cell > input[name=rtd-availability]'; in.select(); in.value = 42;})();

JQuery selector does not work in dynamically created content?

I am trying to retrieve the .html() .val() or something else within a html element, this is my html code (generated dynamically):
<div class="presupuesto"><h2 class="precio" id="precio" value="1202">1.202,00 €</h2>
I need the .val() attribute!
With JQuery and JavaScript I want to show, what option from a select has been selected and then show the information about h2 tag (price). This is my JS code:
$('select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
alert(("#precio").val());
});
The first alert(valueSelected) works well, but the second one triggers a TypeError
Thanks in advance!
As you said that you have dynamically generated elements. Then You need to use event-delegation:-
$(document).on('change','select',function(){
alert($(this).val()); // to get select value
alert($('#precio').attr('value')); // try to use data-attribute which is standered way
});
Note:- Since <h1>,<h2>..,<div>,<ul><li><p>.... these elements don't have value attribute (In standered way). So use data-attribute option for them like below:-
<h2 class="precio" id="precio" data-value="1202">1.202,00 €</h2>
And then change jQuery code just a bit like below:-
alert($('#precio').data('value'));

Insert javascript (jquery) variable in html input field (textbox)

With span and div this works
jQuery
$('#exchange_rate1').html(data[0].FinalCurrencyRate);
HTML
<span id="exchange_rate1"></span>
But if the HTML is an input element such as <input type='text' name='exchange_rate1' id='exchange_rate1' value='<?php echo $post_exchange_rate; ?>> then nothing happens.
Removed php code from value the same nothing.
I also tried document.getElementById("exchange_rate1").html(data[0].FinalCurrencyRate); but I also see nothing.
Now clear, that need to use val. I just searched google for how to insert jquery variable in input field. Could not find.
Use jQueryObject.val(some_value) to set the value of an input, not html().
To be more specific:
// store the value you're looking to assign
var data = [
{ FinalCurrencyRate: <?= $post_echange_rate; ?> }
];
the jQuery way:
$('#exchange_rate1') // grab the <input>
.val(data[0].FinalCurrencyRate); // and assign it from the variable
the straight js way:
// normal JS version:
document.getElementById('exchange_rate1') // grab the <input>
.value = data[0].FinalCurrencyRate; // assign it
Any kind of form fields (<input>,<select>,<textarea>) use .val() to get/set since they don't contain child elements. .html() should be used for structural elements.
In case of text use as
$("#exchange_rate1").val('Hello');
This is because you aren't supposed to be setting the innerHTML of the input element, but the value.
In jQuery you use the .val() method:
$('#exchange_rate1').val(data[0].FinalCurrencyRate);
Or with plain JavaScript, you're changing the value property of the HTMLInputElement object:
document.getElementById('exchange_rate1').value = data[0].FinalCurrencyRate;
For textual input boxes, use .val(), for textareas, use .text(), and for non-input type elements, use .html().
All you need is
$("#exchange_rate1").val('Hello');

Apply PHP script to a single text box

I'm after a simple answer I think.
I have a text box called 'ref' on a page.
When filled in and entered it takes the user to www.website.com/$ref.php.
I need their input to be uppercase to match the directory so I have added this code to change what they type.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
This works great but it is applied to all text boxes on the page.
How do I limit the script to text box 'ref' AND/OR is there a better way of achieving the same effect.
"if (textbox-name=ref) then apply script"
Thanks
Use the jQuery selector you already have:
$("input").keyup(function() {
Change it like this:
$('input[name="ref"]').keyup(function() {
that will select just that one text box and assign the keyup event to it.
jQuery selectors work just like css selectors.
However, if you want to insure that this is the only element that has this keyup function attached, then use an ID attribute.
Select the input by id,
$("#ref").
Your current code is applying the JQuery code to all input elements. To single out just that one, apply an id to the textbox, e.g. id="ref". Then you just reference it by id in your javascript:
$(document).ready(function() {
$("#ref").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
You should also read up on JQuery selectors.
What way did you call this text box 'ref'? if you have class="ref" as an attribute to it, change the selector in jQuery to input.ref. If you have id="ref", change it to input#ref. But you can better do it in php anyway (with strtoupper)

inserting a variable on style tag

I need to change the color of the text based on the drop down list selection.
<select id="room2">
<option>#0808cf</option>
<option>#0E9E26</option>
</select>
<input type="text" id="txtColor">
John: <p style="color:#0808cf" > test </p>
jquery
$('#colors').change(function(){
$('#txtColor').val($("#colors").val());
var fontColor = $('#txtColor').val();
});
I dont want the change to be in the css cause the select id will not be constant. I want it to be inserted in the p style tag. And also i need the text to be John: test to be in one line. I tried this but not working. Thank you.
<p style="color:"+fontColor+" > test </p>
demo: http://jsfiddle.net/kX3EN/
Try - http://jsfiddle.net/kX3EN/7/
$('#colors').change(function(){
$('p').css( 'color', $(this).val() );
});
If you want your "John: test" to be on the same line, you need to:
Change the p (block-level) to something like a span (inline) or
Force the p to act as inline with css (display: inline).
Using jQuery, you need to use the css() function to change the style attribute of an element. Like so:
$('selector for element you want to change').css('color', $("#your-select-element").val());
You'll probably put this in an event handler for your select:
$("select#colors").change(function() {
$("span.changemycolor").css('color', $(this).val());
// 'this', in this case, is your select element
});
got it working by placing the tag after my html code filter. So everytime I append a message will be stored as variable and read as JS when the var is sent to the websocket send method. Thank you

Categories