Jquery get value and display in span - javascript

i've got a select field with few options, each of them has assigned "value" attribute and they got names. Upon selecting one of the options, I want one to be filled with the title, second one with the value. Title works fine, but I can't get it to catch the assigned "value="asd"" value.
$(".itemclass").on("change", function () {
$("span.iclass").text(this.options[this.selectedIndex].textContent);
$("span.impl").text(this.options[this.selectedIndex].val());
});
What am I missing?

Here's how you can access the selected option:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected");
$("span.iclass").text(selectedOption.text());
$("span.impl").text(selectedOption.val());
});
Or alternatively if you prefer to use the DOM node:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected").get(0);
$("span.iclass").text(selectedOption.textContent);
$("span.impl").text(selectedOption.value);
});

Ok I did a little fiddling pardon the pun.
Here is what I came up with.
$(".itemclass").change(function()
{
$("#Name").text(this.options[this.selectedIndex].textContent);
$("#Value").text(this.options[this.selectedIndex].value);
});
Here is my fiddle
http://jsfiddle.net/nH2a3/
Here is where I found your solution Check out the answer for this question for the why.
HTMLInputElement has no method 'val'

Use this:
$(".itemclass").on("change", function () {
$("span.iclass").text(this.options[this.selectedIndex].textContent);
$("span.impl").text($(this).val());
});

You can give it a try with this code:
$(".itemclass").on("change", function () {
$("span.iclass").text($(this).find("option:selected").text());
$("span.impl").text($(this).find("option:selected").val());
});

Related

I get 'Bad assignment' when trying to use $(this) inside function after .load() method

I couldn't find any solutions for my problem yet. Maybe I used wrong keywords.
I'm trying to update the value of an input field onchange after a .load() action has been performed.
Here is my script:
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(this).val('OK');
});
});
So, after someAction.php has been loaded into #actionDiv successfully, I'd like to change the value of that input field, that has been changed.
I have several input fileds, which take this kind of action...
It seems "$(this)" is unknown in the function after load() has been completed.
Can anyone please help?
Thanks
You need to store a reference to the element, or use an arrow method which doesn't change the value of this
$(document).on("change",".myInput",function() {
var that = this;
var value = $(that).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(that).val('OK');
});
});
OR
$(document).on("change",".myInput",function(e) {
var value = $(e.target).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(e.target).val('OK');
});
});
OR
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, () =>{
$(this).val('OK');
});
});

How to pass data- value to jquery function

I have this HTML line with combination of TWIG code:
delete
The line is a part of cycle, so in final result it can be multiple with different value of data-redirect attribute.
I need to pass the value of data-redirect to jquery function, but only a specific value when I click the hyper text link.
$(document).ready(function() {
$('.aaa').on( "click", function(e) {
e.preventDefault();
$.confirm({
title: 'Smazat termín',
message: 'Opravdu chcete smazat tento termín?',
labelOk: 'Smazat',
labelCancel: 'Storno',
onOk: function() {
window.location.assign($(this).attr("data-redirect"));
}
});
});
});
The function works fine except of the line, where I need to redirect to different URL. I need to pass to the window.location.assign() function the specific value from data-redirect attribute.
Actually $(this).attr("data-redirect") does not pass the value from the attribute.
Thank you for help.
Try using. I hope this one helps.
$(this).data('redirect');
I believe is this is an issue. Sorry I just had to.
What I mean is
...
onOk: function() {
window.location.assign($(this).attr("data-redirect"));
^----- may not be referring to what you think it is.
}
...
A quick solution would be to change to to an arrow function like so
onOk: () => { window.location.assign($(this).attr("data-redirect")); }
If you need better support coverage you could assign the variable this as a work around like so
$(document).ready(function() {
$('.aaa').on( "click", function(e) {
var self = this; // <--- here
e.preventDefault();
$.confirm({
title: 'Smazat termín',
message: 'Opravdu chcete smazat tento termín?',
labelOk: 'Smazat',
labelCancel: 'Storno',
onOk: function() {
window.location
.assign($(self)
.attr("data-redirect")); // <--- and here
}
});
});
});

jQuery Eventhandler for an dynamically added object

I got an problem with dynamically added DOM objects in jQuery. First of all I use this:
var $input = $('#search-input');
var $usersList = $('#ulist');
$input.on('input', function () {
$.ajax({
type: 'get',
url: '/userlist',
data: {query: $input.val()},
success: function (response) {
var json = JSON.parse(response);
$usersList.empty();
$.each(json, function (index, val) {
$usersList.append("<div id=\"listelem\">" + val + "</div>");
});
}
});
});
<div id="ulist"></div>
<input id="search-input" type="text">
to insert divs into usersList. This works well, but now I want to get val from this div when I click on it to process it further. I wrote this piece of code:
$usersList.on('click','#listelem', function(){
alert("clicked");
});
When I click on div I got proper alert, but now I have no idea how could I took data from inside of this element.
I don't know the proper engineering but I have dealt with similar issue while I was developing some requirements. basically as I understood you want to find out the target of the event and drag a value from there? if so you can do something like this:
jQuery(document).on('click', '#listelem', function(event){
var x = event.target.val();// event.target.value; depending on your situation and availability of the method.
});
Hope this helps.
try this
$(document).on('click','#listelem', function(event) {
alert($(event.target).text());
});
jsfiddle
Thanks you for help. for me proper option was to call
var mem =event.target.innerText;
you can do that with the regular javascript, you don't need Jquery.
document.addEventListener("click", function(e) {
if(e.target) {
console.log("item clicked ", e.target.textContent);
}
});
This should do the job to get the value of current target.

Select2 onchange not working

When I've added select2 to all selects in my app it worked very nice except when in my select is this property(it works when I don't use select2):
onchange="'refresh()'"
Function refresh:
function refresh()
{
document.forms[0].submit();
}
This is how I run select2
$("select").each(function(){
var this1 = $(this);
if(this1.attr('multiple')!='multiple')
{
this1.select2();
}
});
How to pass this? Or maybe there is some mechanism inside the select2 that deals with that kind of problems? All kinds of suggestions are welcome:D
you need to update this:
$(#Select/Input Element).select2();
$("#select/input element").change(function () {
var valueToSet = $("#select/input element").select2('data').text;
$('#hiddent field to which data to be set').val(valueToSet);
});
Not sure to understand. When one of yours selects changes, you want to call the refresh method? In that case :
$("select").each(function(){
var $this = $(this);
if($this.attr('multiple')!='multiple'){
$this.select2();
$this.change(refresh);
}
});
Remove single quote from onchange="'refresh()'. Try as mentioned below :
<input type="checkbox" onchange="Refresh();"/>
And your script will be defined as below :
<script type="text/javascript">
function Refresh() {
alert('refresh');
}
</script>

Refer to immediate selector object with jQuery?

I'm trying to learn some jQuery, and I setup a test page with the following code:
<a id='encode' href='javascript: void(0)'>encode</a> |
<a id='decode' href='javascript: void(0)'>decode</a> |
<br/>
<textarea id='randomString' cols='100' rows='5'></textarea>
<script type='text/javascript'>
$(document.ready(function () {
$('#encode').click(function() {
$('#randomString').val(escape($('#randomString').val()));
});
$('#decode').click(function() {
$('#randomString').val(unescape($('#randomString').val()));
});
});
</script>
The idea is I can put something in the textarea and click either "encode" or "decode", and it will either escape or unescape what I put into the textarea.
This code works just fine, but my question has to do with how I am changing the value of the textarea. In my code, I am selecting the textarea value twice: once to (un)escape it, and once again to change the value. IMO this seems clunky and maybe unnecessary. I thought maybe I could do something like this instead:
$('#randomString').val(escape(this));
But this seems to refer to the object of the link I clicked, not the #randomString selector, so is there some other magic word I can use to reference that $('#randomString')?
$('#randomString').val(escape(this));
This does not get the object you want. It is effectively the equivalent of doing this:
var foo = escape(this);
$('#randomString').val(foo);
this only means something different when you start a new scope with a function definition.
jQuery does offer this kind of functionality with a callback option:
$('#randomString').val(function (idx, oldVal) {
return escape(oldVal);
});
The second parameter is the current value of the element; the return value sets a new value for the element.
You can try this
$(document.ready(function () {
$('#encode').click(function() {
var $randomString = $('#randomString');
$randomString.val(escape($randomString.val()));
});
$('#decode').click(function() {
var $randomString = $('#randomString');
$randomString.val(unescape($randomString.val()));
});
});
The short answer, if I understand you correctly, is no. There isn't a way to refer to $('#randomString') where you're talking about. It's just a parameter to the val method, so it's just plain JavaScript syntax, no jQuery "magic".
To accomplish the task at hand and make the code cleaner and less clunky, I would save off the jQuery object for #randomString so you don't have to keep creating it:
$(document.ready(function () {
var $rndStr = $('#randomString');
$('#encode').click(function() {
$rndStr.val(escape($rndStr.val()));
});
$('#decode').click(function() {
$('#rndStr').val(unescape($rndStr.val()));
});
});
You could make it a little generic:
$.fn.applyVal = function(func) {
return this.each(function() {
$(this).val( func( $(this).val() ) );
});
};
Then the following call is enough:
$('#randomString').applyVal(escape);

Categories

Resources