How define dynamic Select Options - javascript

I have a function for replace or/and populate dinamic inputs. I paste one text in textarea and the function find input referenced and add the value. This works fine.
Bellow my code:
input.addEventListener('focus', function(){
var content = input.value;
content.replace(/(\S+): ?(.+)/g, function(m, id, value) {
var field = $('input[data-alias-import="'+id+'"]');
var element = document.getElementById(field.attr('id'));
//console.log(element.attr('id'));
if (element) element.value = value;
});
});
In this case, the variable input is my textarea.
My question is, what the best way to make a same thing with a Select? How I can find a specific value in select and defined this "SELECTED".

If you want to get the selected option of a select element you can use jQuery to do something like this:
$("#elementID :selected").val();

Related

Appending to combobox field in ExtJS

I have a combobox with a text. When you select the element from the dropdown it must be appended to the field of the combobox but not replaced.
I've tried this:
beforeselect: function (combo, record) {
var rawVal = this.rawValue;
...............
record.data.Value = rawVal + record.data.Value;
}
But this code adds to the store modified version of record, so it is not what I need. I need store haven't modified.
If I get your question clearly, the field you need is tag field not combobox. You can check the example from below link.
http://examples.sencha.com/extjs/6.0.2/examples/kitchensink/#form-tag
You do not need to do any record operayion by using tag field. If you have any further question, let me know.

Dynamically add option to chosen select multiple JQuery plugin

I want to add the text that a user inputs in the text field of a chosen select multiple input as an option, and automatically select it, all of this when the option doesn't exists, if the option exists, then I would like to select it. So far I have manage to do this:
Chosen.prototype.add_text_as_option = function () {
$('#id_select').append(
$('<option>')
.html(this.search_field.val())
.attr('selected', 'selected')
.attr('value', 0)
);
$('#id_select').trigger("liszt:updated");
return false;
};
I call this function whenever the users presses enter while the input field is in focus within the keydown_check function.
I have two problems:
Top priority, when the user presses enter and has typed a substring of an option, the option won't get selected, but the substring text will be added and selected. Not what I want.
For instance: If I have the option "foo", and start typing "fo", chosen will mark the first
option as candidate ("foo"), so if I press enter, it should be selected, but instead, what happens is that "fo" is added as an option and selected, when I actually wanted to select "foo".
If I select "foo" with a click, then everything works fine. The option chosen marks is selected and the substring text is taken as part of the option.
How can I add a non existent option to chosen, without loosing all the original functionality?
How can I access the select multiple field I initilized whith chosen inside the chosen plugin? As you can see in the code above, the id of the select multiple field is hardcoded. I want to do this to be able to refresh the select when the user adds a new option.
The functionality that I'm looking for is very similar to the skills widget of linkedin
You should try out the select2 plugin which is based off of chosen plugin but it works well with adding elements dynamically.
Heres the link: http://ivaynberg.github.com/select2/
Look at the example for auto-tokenization I think that might be what you are looking for.
I needed this today so I wrote something like this:
$(function() {
// form id
$('#newtag').alajax({
// data contains json_encoded array, sent from server
success: function(data) {
// this is missing in alajax plugin
data = jQuery.parseJSON(data);
// create new option for original select
var opt = document.createElement("OPTION");
opt.value = data.id;
opt.text = data.name;
opt.selected = true;
// check if the same value already exists
var el = $('#tags option[value="' + opt.value + '"]');
if( !el.size() ) {
// no? append it and update chosen-select field
$('#tags').append( opt ).trigger("chosen:updated");
} else {
// it does? check if it's already selected
if(!el[0].selected) {
// adding already existent element in selection
el[0].selected = true;
$('#tags').trigger("chosen:updated");
} else {
alert("Already selected and added.");
}
}
}
})
});
"#"newtag is a form, ".alajax" is a plugin that sends form data in async way and returns server's response in JSON format. In the controller I check if a tag exists otherwise I create it. In response I five "jsoned" tag object.
I created a jsfiddle of jquery chosen which takes text and create as option. In earlier version of jquery chosen have facility create option.
create_option: true;
persistent_create_option: true;
skip_no_results: true;
You can use this code:
$('#id_select').chosen({
width: '100%',
create_option: true,
persistent_create_option: true,
skip_no_results: true
});
jsfiddle link: https://jsfiddle.net/n4nrqtek/
just call it keyup_check
keydown_check is called before the pressed letter is initialized
unlike keyup_check
I found a solution multiple select
var str_array = ['css','html'];
$("#id_select").val(str_array).trigger("chosen:updated");

Select attribute not changed after change of select element

I have a table in which a few columns contains select elements. In the tfoot I have one input element for each row used for filtering the row based on the selected value in the select element.
When loading the table and directly filtering the columns with selects, than it works and the table is filtered.
But when making a change in the select elements, the filter function is not taking any notice that the value has changed.
Checking out the html I can see that the "selected" attribute is still on the option that was selected when loading. Hence, it doesn't get updated when making an actual changed (identified in both FF and Chrome).
But from jQuery, searching for the selected value (.find(":selected")) works. So I figure that I can use that to find the value and then set the selected attribute to whatever was selected. This is how I am trying to do it:
$("select[id^='qu_owner']").live('change', function (e) {
var owner = $(this).val();
console.log(owner);
var ticketid = $(this).attr('id').substr(9);
$($(this) + " option[value=" + owner + "]").attr("selected", "selected"); //Update: this has been removed
});
But the selected attribute is still not updated in the element.
Any clue how to do this? I need the filtering to work and it's looking at the selected attibute. Is it not possible to make this kind of update to the select element?
UPDATE
Ok, based on the comments and answers below I understand there are better ways of doing what I did above. So instead of using $(this).find(":selected").val(); I now use $(this).val();. Also, I did remove the last row since I understand one shouldn't try to set the selected attribute.
And also, I now understand that the code where I have the actual problem is the filter function. This is for DataTables so it's a plugin but this is the significant part:
aData[i] is the actual table cell. Hence, it's just text but in this case it's the text for my select element. I think below is heading in the right direction, but still not working (check comments next to console.log-rows):
function( oSettings, aData, iDataIndex ) {
var ret = true;
//Loop through all input fields i tfoot that has class 'sl_filter' attached
$('tfoot .sl_filter').each(function(i, obj){
//$(this) can be used. Get the index of this colum.
var i = $("tfoot input").index($(this));
//Create regexp to math
var r = new RegExp($(this).val(), "i");
//Get the selected option from the column
console.log($(aData[i]).attr('id')); //Properly prints the ID
console.log($(aData[i] + " option:selected").text()); //Prints all options, not only the selected on
console.log($(aData[i] + " option:selected").val()); //Prints the value of the id that was selected when data was loaded, even if a new option has been chosen
console.log($(aData[i]).val()); //Prints the value of the id that was selected when data was loaded, even if a new option has been chosen
var str = $(aData[i] + " option:selected").text();
/*Test to see if there is a match or if the input value is the default
(the initial value of input before it has any fokus/text) */
if(r.test(str) || $(this).val()=="Search"){
//Return true only exits this function
return true;
}else{
/*Return false returns both function an .each. Retain 'false' in a variable scoped
to be reached outside the .each */
ret = false;
return false;
}
});
//Return true or false
return ret;
}
It is the text for the selected element I need to get hold of. That's what should be filtered upon. How can I do that?
Update
To narrow it down, I have created a jsfiddle with what's necessary. It's all about how to extract the text from the selected option: jsfiddle
aData[i] = the table cell. In jsfiddle, i use "sel" as variable for the content of the cell. The text for sel is copied form aData[i].
There's no need to change the attribute of the <option> - that's supposed to contain the original state of the element as it was downloaded from the server.
Your filter should be checking the selected property of the chosen option, e.g.:
.filter(function() {
return this.selected; // check the boolean property
})
This is also how the :selected pseudo-selector works - it checks the current value of the property, not the attribute.
Note that in the change handler for a <select> element, you can just use this.value to get the currently selected value.
$('select').on('change', function() {
// current value
var value = this.value;
// text of the currently selected option.
var text = this.options[this.selectedIndex].text;
}

switching selections between two select menus

I'm trying to build some kind of currency converter and I have two select menus with the list of currencies.
I want to create a button that when clicked, it will switch the selection between the "from" select menu and the "to" select menu.
how do I implement it using the select menus I already have?
I believe you'r looking for a swap behavior.
http://jsfiddle.net/brentmn/D55Dm/
$(function(){
var $sel1 = $('#currency1');
var $sel2 = $('#currency2');
$('input[type=button]').click(function(){
var val1 = $sel1.val();
var val2 = $sel2.val();
$sel2.val(val1);
$sel1.val(val2);
//jqueryui
//$sel2.val(val1).trigger('change');
//$sel1.val(val2).trigger('change');
});
});
Something like this?
$("#button").on("click", function() {
var from = $("#from").val();
var to = $("#to").val();
$("#from").val(to);
$("#to").val(from);
});
I'd really do it with less code than that, but have done it like that for readability.
Assuming I've understood you correctly, you want a button that will swap the values of two select elements. If that's right, try something along these lines:
$("#someButton").click(function() {
var elemTo = $("#to"),
elemFrom = $("#from"),
toVal = elemTo.val();
elemTo.val(elemFrom.val());
elemFrom.val(toVal);
});
It simply gets references to the two select elements (assumed here to be #to and #from), gets the value of one of them, replaces the value of that one with the value of the other, and then replaces the value of the second with the stored value from the first.
Note that this assumes both select elements have the same option values. If an option is present in one select but not the other, it would not work.
Here's a working example.
If you dbl click on one item in 'From' section , it will get selected be appended to the 'To' section.
$("#selectFrom").dblclick(function(){
$selectTo.append($selectFrom.children(":selected"));
});
Which all functionalities you want??

Populating div in real time with form input data

I have a form (just one field) which I am populating with some data. I would like to get me Div container populated with the data I put there in a real time. So no refresh, after I type in some text in the form field, I get it in the div as well. Does anybody know how to do it? JQuery, AJAX?Any advice appreciated.
var div = $('div')[0];
$('input').bind('keyup change', function() {
div.innerHTML = this.value;
});
Try it out: http://jsfiddle.net/H6P2z/
Of course you should make the selectors specific to your actual elements.
With jQuery you can do this very easily:
$('#textFieldId').bind('change', function (event, previousText) {
$('#divId').html($(this).val());
});
You could bind an onkeyup event to the input field. When the event fires, you can grab the contents of the field and do what you want with it.
This might look like this:
$(selector).keyup(function(e) {
// find the value of the field
var text = $(this).val();
// do something with it
$(yourDivSelector).html(text);
});

Categories

Resources