jquery clone an input doesn't see changes to the value - javascript

I have a form with hidden inputs.
I .clone() them and show them to the user in a .dialog().
The user makes some changes and i use .val() to change the hidden fields.
However the next time i clone the form(without reloading the page) i have the initial values again, and never the updates ones.
There seems to be this weird bug/result? see http://jsfiddle.net/YvBfP/ (broken for visible input too)
$(this).closest('td').find('button').click( function ()
{
var d = $('#pagamento_anticipato').html();
$(d).dialog({
modal: true,
width: 400,
height: 300,
close: function( event, ui ) {
var importo = $(this).find('input[type="text"]').val();
var descrizione = $(this).find('textarea').val();
var select = $(this).find('select').val();
$(this).remove();
$('#pagamento_anticipato').find('input[id="importo"]').val( importo );
$('#pagamento_anticipato').find('#descrizione').val( descrizione );
$('#pagamento_anticipato').find('#tipo').find('option[value="' + select + '"]').attr('selected', true);
}
});
return false;
});

using .val() sets/gets the current value and not the attribute for the element.
$(element).val(value) // sets current value
$(element).val() // <-- will always return the current value
to change the attribute you have to use .attr()
$(element).attr('value',value)
Then you will see the change in the HTML
http://jsfiddle.net/wirey00/bJjjw/
EDIT:
Just found out this doesn't work with jQuery 1.5.x and lower.. tested it with jQuery 1.6.0+ and it worked fine

You are setting the value property of the input but checking to see if the value attribute has changed. To see the elements value use .val() don't check its html. However if you need to change the elements value attribute use setAttribute
$('#money')[0].setAttribute('value', 3000);
http://jsfiddle.net/YvBfP/4/

Related

django-select2 programatically setting value

I'm using Django-select2 to show select2 widgets on my forms.
On one of these form select-fields I want to user to be able to set the value by clicking a link containing a suggestion.
My javascript looks like:
<script type="text/javascript">
$( document ).ready(function() {
// When the topicSuggestion is clicked, populate the select2 field with that value.
$('#topicSuggestion').on('click',function (e) {
var value = {{ object.suggestion.topic.id }};
$('#id_topic').val(value).trigger('change');
});
});
</script>
This isn't quite working as expected though. Instead of nicely populating the value, this is the behaviour I see:
Click the link, nothing happens
Select a random value from the list, and click the link. The select seems to clear
Select the desired value once, now click a random value and click the link. Now the value populates correctly
I can imagine this is related to my non-existing js skills. Could someone be kind enough to help me clear this up on this newyears day?
As we can see in https://github.com/codingjoe/django-select2/discussions/145
the items are loaded async. So if you want to pre-populate, you need to add the value first.
The select2 docs explain this: https://select2.org/programmatic-control/add-select-clear-items#create-if-not-exists
The answer in this case is:
$( document ).ready(function() {
// When the topicSuggestion is clicked, populate the select2 field with that value.
$('#topicSuggestion').on('click',function (e) {
$( "#topicSuggestion" ).css( "border", "9px solid red" );
var data_id = {{ object.suggestion.topic.id }};
var data_name = "{{ object.suggestion.topic.name }}";
// Set the value, creating a new option if necessary
if ($('#id_topic').find("option[value='" + data_id + "']").length) {
$('#id_topic').val(data_id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data_name, data_id, true, true);
// Append it to the select
$('#id_topic').append(newOption).trigger('change');
};
});

jQuery ui autocomplete get selected item in other function

I have a problem with jQuery autocomplete, I try to get the value of the input but I get the label but no the value.
var listeClients = [{"value":1,"label":"Orange"},{"value":2,"label":"Blue"}];
$( "#site_client_first" ).autocomplete({
source: listeClients,
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
And for get the value I use :
$("#site_client_first").val();
https://jsfiddle.net/fyz8vL3a/
How to get the value ?
Thanks by advance =)
In the select event of autocomplete, you are setting the label as value property of element #site_client_first i.e. here $("#site_client_first").val(ui.item.label). Hence when you try to set the span's innerHTML by assigning $("#site_client_first").val(), you will always get the label and not your item.value.
Try the code below. I have added an attribute 'itemValue' to $("#site_client_first"). This will hold your item's value and $("#site_client_first").val() will hold the item's label.
And when setting up the span innerhtml, you assign $("#site_client_first").attr("itemValue") which is your item's value.
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
Make change to the above line in your HTML change.
Your final html is as belows:
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
<button onclick="getValue()">Get</button>
<span id="svalue"></span>
Your script goes here:
$(document).ready(function() {
var listeClients = [{ "value": 1, "label": "Orange"}, {
"value": 2,
"label": "Blue"
}];
$("#site_client_first").autocomplete({
source: listeClients,
select: function(event, ui) {
$("#site_client_first").val(ui.item.label);
$("#site_client_first").attr("itemValue", ui.item.value);
return false;
}
});
})
var getValue = function() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}
function getValue() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}
The problem is you are trying to use an input element as a select element.
Unlike for a select, the value for an input is simply what is written in it.
The default behavior of the autocomplete plugin is to display the labels of given source as suggestions, and when you select one them it sets the corresponding value in the input. You are overriding this functionality in the code below, by setting the label as value of the input:
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
If you were to remove the piece of code above, you would notice that the value field will be written in the input element upon selection of an option.
Solution 1
I recommend replacing your input element with a select one. Which I think better suits your needs. If you need to search through the options you may want to use a plugin like chosen or select2.
Solution 2
If you're keen on using an input with autocomplete, set the value as an extra attribute in the select callback
select: function (event, ui) {
$("#site_client_first").val(ui.item.label); // what the user sees
$("#site_client_first").attr('data-realValue', ui.item.value); // value is hidden
return false;
}
You can retrieve the value using
$("#site_client_first").attr('data-realValue');
Demo: https://jsfiddle.net/fyz8vL3a/1/

How to clear a selected value in Selectize.js dropdown?

I have a selectize.js dropdown and I have to clear the selected value .
I have tried this (as suggested in another question):
var selectize = $("#optionNetFlow")[0].selectize;
selectize.clear();
But it gives the following error:
When I change it to this:
var selectize = $("#optionNetFlow").selectize;
selectize.clear();
I gives this error:
What I am doing wrong here?
I finally found the answer here Selectize.js Demos
What works for me is:
var $select = $('#optionNetFlow').selectize();
var control = $select[0].selectize;
control.clear();
what I was missing var $select = $('#optionNetFlow').selectize(); before applying the solution provided in above question's answer.
Now I am to get all the functions in console like :
Try this,
$("#optionNetFlow")[0].selectize.clear();
Try this out:- http://jsfiddle.net/adiioo7/2gnq1ruv/204/
JS:-
jQuery(function ($) {
var $select = $('#input-tags').selectize({
persist: false,
create: true
});
$("#btnClear").on("click", function () {
var selectize = $select[0].selectize;
selectize.clear();
});
});
All other answers either clear a single selectize or need a specific reference to the selectize in the moment of it's creation.
The solution below, on the other hand, works for any number of selectize elements you have inside any form; you just need to specify the desired form:
$('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })
The rationale is that Selectize keeps the original element in the DOM (hiding it), adds a reference to the selectize on the .selectize property of the DOM element and adds a CSS class selectized to it.
So the solution finds all the elements that have the CSS class selectized, loops through them and calls element.selectize.clear().
$(document).on('click', 'div.selectize-input div.item', function(e) {
var select = $('#services').selectize();
var selectSizeControl = select[0].selectize;
// 1. Get the value
var selectedValue = $(this).attr("data-value");
// 2. Remove the option
select[0].selectize.removeItem(selectedValue);
// 3. Refresh the select
select[0].selectize.refreshItems();
select[0].selectize.refreshOptions();
});
This do not remove the item from the select, just remove it from the selected options.
Or if you have multi select, and do want to restore selected items in the drop-down list (hide selected set to true).
var selectize = $("#select-item").selectize;
//clone array
var items = selectize.items.slice(0);
for (var i in items) {
selectize.removeItem(items[i]);
}
selectize.refreshOptions();

Jquery input value not showing up correctly

I have something very simple to just get an input value.
The code looks like this:
var $a = $('.custom-amount').val();
$('.custom-amount').on('change', function() {
alert($a)
})
And my input:
<div class='custom-amount'>
<input placeholder='Custom Amount' type='text-area'>
For some reason, my alerts are empty. Does anyone see whats going wrong?
Change your selector to $('.custom-amount input'), and get the value after the change event is fired, e.g.
$('.custom-amount input').on('change', function() {
var a = $(this).val();
alert(a);
});
Right now, you are trying to get the value of a div, which won't work. You need to get the value of the input.
Edit: also, it looks like you are trying to display a textarea. Try replacing this...
<input placeholder='Custom Amount' type='text-area'>
With this...
<textarea placeholder='Custom Amount'></textarea>
This may help:
http://jsfiddle.net/d648wxry/
The issue is very simple, you are getting the value of the div element. Instead you should retrieve the value of the input element so the 'custom-amount' class must be added to the input.
Also you need to execute the val() method inside the event to get the value updated.
var $a = $('.custom-amount');
$('.custom-amount').on('change', function() {
alert($a.val());
});
Cause your div has no value. Change your code to:
var $input = $('.custom-amount input');
$input.on('change', function() {
var $a = $input.val();
alert($a)
})
First of all, you only assign to $a outside of the change function. This would be more clear if you kept your code lined up better (see the edit I made to your post). This is the right way to do it:
$('.custom-amount').on('change', function() {
var $a = $('.custom-amount').val();
alert($a)
});
Second of all, the class custom-amount is assigned to a <div> instead of the <input> element. You have to select the <input> element, not the <div>. Change your markup to:
<div>
<input placeholder='Custom Amount' type='text-area' class='custom-amount'>
</div>

"defaultValue" property for <select>?

Javascript has textObject.defaultValue=somevalue for retrieving the default value (stored value from page load) of an input even if you wipe the input and replace the contents, you can still get the default back. Like this:
// in the html page
<input id="addr1" type="text" value="21 Oak St." />
// the jquery
myInput = $("#addr1"); // the input, default value on page load = 21 Oak St.
$(myInput).val('51 New St'); // wipe default and set new
// alerts 21 Oak St
alert($(myInput).val($(myInput)[0].defaultValue));
How do you accomplish this on a select?
selectedIndex is boolean, not the value, so that does not work.
Thanks!
You probably want to look at the "defaultSelected" attribute of "option" elements.
Initially, "defaultSelected" will be true if the original HTML of the option tag had an explicit "selected" attribute. You can change that by setting the attribute on option tags with Javascript after the page has loaded, in response to whatever conditions you like.
This is the jquery that works for me:
$('select[name="name_of_select"] option[selected]').val()
with Jquery we can do sth like this :
$('select[name="type_id"] option').map(function()
{
if($(this).attr('defaultSelected')==true) return this
}).get(0).value;
This will return the default Selected option value
:)
I used the following to loop through a forum, check their default values and their current values.
if the script comes a cross a single selectbox it will loop through the children on the selectbox.
oFormObject = document.forms[0];
for(i=0; i<oFormObject.elements.length; i++)
{
oValue = oFormObject.elements[i].value;
oType = oFormObject.elements[i].type;
if(oType=='select-one') {
for(k=0; k<oFormObject.elements[i].children.length; k++)
{
if(oFormObject.elements[i].children[k].defaultSelected==true){
oformElement = oFormObject.elements[i].children[k].value;
}
}
}else{
oformElement = oFormObject.elements[i].defaultValue;
}
console.log(oformElement);
console.log(oValue);
console.log(oType);
}
there may be multiple "selected" option elements, in that case pick the first if no other requirements are set. #Pointy tip is correct but be aware that the "defaultValue" property can be overwritten by other code in the same page. If it were read-only it would be more useful :-)
I found a shortest way to do this :
$('select#myselect').find('option[defaultSelected]');
I run this on page load to manually set the defaultValue for Select boxes.
// Set a default value property on selectboxes (for reverting)
$('select').each(function(index,ele) {
var origvalue = $(this).val(),
defaultvalue = $(this).prop('defaultValue');
// If the default value hasn't already been set for this selectbox
if(!defaultvalue) {
$(this).prop('defaultValue', origvalue);
}
});
The simplest way to do this is:
$('#selectbox option').prop('selected', function() {
return this.defaultSelected;
});

Categories

Resources