jQuery .val() not setting the value of <select> - javascript

I would like to know why jQuery's .val() function is not setting the value of the <select> control for me after I called replaceWith, but it is working otherwise.
Please see here for a (not) working example.
<select><option>ABC</option><option>DEF</option></select>
<input type="button" onclick="ControlOff()" value="Turn Off Control" />
<input type="button" onclick="ControlOn()" value="Turn On Control" />
<input type="button" onclick="Test()" value="Value Setting Test" />
function ControlOff() {
$('select').each(function () {
$(this).replaceWith('<span class="select-type">' + $(this).val() + '</span>');
});
}
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$(this).val(selected);
});
}
function Test() {
$('select').val('DEF');
}

The problem is, that $(this) in $(this).val(selected) refers to the removed <span> element, not your new element. You need to replace it with:
$('select').val(selected);
to grab the previously inserted new element.
Also, your code is unecessarily complex, this does the same thing, but simpler:
function ControlOn() {
$selectText = $('.select-type');
var selected = $selectText.text();
$selectText.replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$('select').val(selected); // Use an id instead to match: #my-select-id
}
Make sure to give the <select> element an ID, otherwise it's going to mess up once you introduce a new <select> element somewhere else on the page.
See here for a working example.

The problem is that in ControlOn you have an each which is looping over .select-type elements which are span's and spans cannot be set with the val method:
You can fix this by changing the method to this:
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
var $select = $('<select><option>ABC</option><option>DEF</option></select>');
$(this).replaceWith($select)
$select.val(selected);
});
}
Live example: http://jsfiddle.net/qSYYc/4/

set value of options will solve your problem. jsfiddle
<select><option value='ABC'>ABC</option><option value="DEF">DEF</option></select>

function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith($('<select><option>ABC</option><option>DEF</option></select>').val(selected));
});
}
Rewrite your code like above, it would work!
The element referenced by this won't change to the select element you just created, it will always be the span element inside the scope of that function. Therefore you should set the value to the newly created select instead of the invariant $(this)!

I'd suggest you to use "disabled" attribute to turn select on and off, it, won't mess up the .val() functionality
function ControlOff() {
$("select").attr("disabled", "disabled");
}
function ControlOn() {
$("select").removeAttr("disabled");
}

Related

Check if input value is not the same onBlur

How can I check if the value of an input box is not the same after blur?
$("#username").on('blur', function() {
$("#usertext").append("new input<br>");
})
Check this jsFiddle: https://jsfiddle.net/xztptsdg/
Let's think that I enter "Josh" in input and after blur, will append new input box. But, user can "re-blur" the username input, and will append other input.
I want to check if the value is the same, not append new input.
You may use change instead of blur, for example:
$("#username").on('change', function() {
$("#usertext").append("new input<br>");
});
So, there is no need to check if the value changed or not because the change event is sent to an element when its value changes.
See this fiddle
You can keep a global variable to store the current value of the textbox and then check whether the entered value is the same as the previous one. If not, then append the new input text and also set the global variable with the new one. Below is the Javascript that does this.
JS
var txt = "";
$("#username").on('blur', function() {
if (txt != this.value) {
$("#usertext").append("new input<br>");
txt = this.value;
}
})
I would suggest you to use change(). According to the docs
The change event is sent to an element when its value changes.
See the fiddle and below is the JS code with change().
$("#username").change(function() {
$("#usertext").append("new input<br>");
});
You can do it like following snippet.
var text = '';
$("#username").on('blur', function() {
if(this.value != text){
text = this.value;
$("#usertext").append('new input<br>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="username" id="username">
<br>
<span id="usertext"></span>

How can I add to the end of the string that already exists in input field?

Now, If I hit the button, it clears all in the input field, and it automatically inputs "#marry" to it.
But, I don't want it to be cleared:(
What if I want to add "#marry" to the end of the strings that already exists in the input field?
How can I customize my javascript part?
Input field
<textarea class="box text_area" cols="10" id="input" name="comment[body]"></textarea>
button
<a href="#topic" id="username" value="#marryā€¯><span class='btn'>reply</span></a>
javascript
$(document).on('click', 'a#username', function() {
$(".box#input").val($(this).attr('value'));
}
val() has a callback with the arguments index and value, you can use that to easily add something to the value.
$(".box#input").val(function(_, val) {
return this.value + 'some extra string';
});
$(document).on('click', 'a#username', function() {
var self = this;
$(".box#input").val(function(_, val) {
return val + self.value;
});
});
First of all adeneo's answer is good and you should read it. Here is an alternative solution that does not use jQuery:
I assume that both these elements are a part of a form. Let's say for instance the form has an ID of "post". We can access it using document.forms and then its fields as such:
var input = document.forms.post["comment[body]"];
Now, we can add to its value whenever the button is clicked. First select username with getElementById or querySelector and then add the event:
username.addEventListener("click", function(ev){
input.value += ev.target.value;
});
Or with jQuery (this also delegates if the element is not in the DOM yet):
$(document).on('click', 'a#username', function() {
input.value += this.value;
});
It might be desirable to append an extra space between the current text and the username.
append #marry at the end of text area. you can use bellow code its working fine.
$(document).on('click', 'a#username', function () {
var txtvalue = $(".box#input").val();
$(".box#input").val(txtvalue + $(this).attr('value'));
});
see jsfiddle link http://jsfiddle.net/F6mkh/1/

Jquery Show Input Text Based On Input Value

I facing problem with my jquery, on showing input text based on input value.
Here is the JS fiddle demo :
http://jsfiddle.net/Ltapp/364/
When I try to input #hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.
JS code :
$(window).load(function(){
var myString = '#hotmail';
$('#hotm').hide();
$("input").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
});
It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here
$("input:first").keyup(function () {
var value = $(this).val();
if(value.match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
As many has said, you are binding the event on all the inputs I did a little change:
$(function(){
var myString = /#hotmail/ig;
$("#check").bind('keyup checkvalue', function() {
$('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
}).trigger('checkvalue');
});
using regex if you are using #HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.
demo: http://jsfiddle.net/voigtan/xjwvT/1/
You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.
See JSFiddle Here:
http://jsfiddle.net/Ltapp/366/
<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>
var myString = '#hotmail';
$('#secondinput').hide();
$("#firstinput").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#secondinput').show();
} else {
$('#secondinput').hide();
}
});
use this for your if part :
if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide
<input id="hotmail" type="text"/>
and then
$("#hotmail").keyup(function () {...});

Append input value to a div

can someone show me how to take an input value and append it to a div once the user clicks on an Add link?
This is the best I could do.
HTML:
<div id="customUtility-container"></div>
Add
jQuery:
$(function() {
var addDiv = $('#customUtility-container');
var i = $('#customUtility-container').size() + 1;
$('#addUtility').live('click', function() {
$('#customUtility').val().appendTo(addDiv);
$('<p><label for="customUtility-container"><input type="text" id="customUtility" size="20" name="customUtility_' + i +'" value="" placeholder="" /></label> Remove</p>').appendTo(addDiv);
i++;
return false;
});
$('#removeUtility').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
This creates another input field however; I just want to have one input box, have the user click Add, then it takes that value, puts it into the list, and clears the input box so the user can add something else again.
Use jQuery's append() function
addDiv.append($('#customUtility').val());
Here's a working fiddle.
Warning: opinion below
When creating a variable to store a jQuery object, I think it's helpful to prefix the variable with $. This way, you know that you're working with a jQuery object. It also makes it easier for those coming behind you to recognize what you're doing:
var $addDiv = $('#customUtility-container');
$addDiv.append($('#customUtility').val());
Something like:
addDiv.html(addDiv.html() + whateveryouwanttoadd)
addDiv.append($('#customUtility').val());
Change
$('#customUtility').val().appendTo(addDiv);
To
addDiv.append($('#customUtility').val());
val() method gives the value of the input element and you cannot call a jQuery method on a string which will throw an error.
Working demo - http://jsfiddle.net/t9D8R/
I ended up scrapping everything and redoing it:
$(function() {
var i = $('#customUtility-container').size() + 1;
$("#addUtility").on("click", function() {
$("#customUtility-container").append('<div id ="customUtility_' + i +' " name="customUtility_' + i +' ">'+ $("#customUtility").val() + 'Remove</div>');
});
$('#removeUtility').live('click', function() { $(this).closest('div').remove();
i--;
});
});

How to get previous and new selected value from a option DOM element with JavaScript?

How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?
<select size="1" id="x" onchange="doSomething()">
<option value="47">Value 47</option>
...
function doSomething() {
var oldValue = null; // how to get the old value?
var newValue = document.getElementById('x').selected.value;
// ...
Thank you! :)
Using straight JavaScript and DOM, something like this (live example):
var box, oldValue;
// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
// DOM2 standard
box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
// IE fallback
box.attachEvent("onchange", changeHandler);
}
else {
// DOM0 fallback
box.onchange = changeHandler;
}
// Our handler
function changeHandler(event) {
var index, newValue;
// Get the current index
index = this.selectedIndex;
if (index >= 0 && this.options.length > index) {
// Get the new value
newValue = this.options[index].value;
}
// **Your code here**: old value is `oldValue`, new value is `newValue`
// Note that `newValue`` may well be undefined
display("Old value: " + oldValue);
display("New value: " + newValue);
// When done processing the change, remember the old value
oldValue = newValue;
}
(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)
Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.
But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.
Look here: Getting value of select (dropdown) before change
I think the better,
(function () {
var previous;
$("select").focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
// Do something with the previous value after the change
alert(previous);
});
})();
The following code snippet may help
<html>
<script type="text/javascript">
this.previousVal;
function changeHandler(selectBox)
{
alert('Previous Val-->'+selectBox.options[this.previousVal].innerHTML)
alert('New Val-->'+selectBox.options[selectBox.selectedIndex].innerHTML)
this.previousVal=selectBox.selectedIndex;
}
</script>
<body>
<select id="selectBox" onchange="changeHandler(this)">
<option>Sunday</option><option>Monday</option>
<option>Tuesday</option><option>Wednesday</option>
</select>
<script type="text/javascript">
var selectBox=document.getElementById("selectBox")
this.previousVal=selectBox.selectedIndex
</script>
<body>
</html>
Below worked for me.
Add below two events to your select HTML tag:-
onFocus='this.oldValue = this.value'; //if required in your case add this line to other events like onKeyPressDown and onClick.
onChange = 'alert(this.oldValue); this.value=this.oldValue'

Categories