SELECT2 -> Add data without replacing content - javascript

I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.
Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.
Instead, each tag is replacing the content and adding itself.
I need the adding to be appended into the box without replacing what's already in there.
Here's my code:
$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
The data is being pulled through via AJAX with a span around each suggested tag.
Hope I'm clear enough.
Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.
Thanks

You should be able to do that with simple:
var test = $('#test');
$(test).select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate"},
{id:3,text:"invalid"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px"
});
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Working example: http://jsfiddle.net/z96Ca/

You are replacing the value with val(mystuff). You want to do the following:
Get the current data in the input with val()
var dataOld = $('#selectPretty').val();
Append the new data with something like*
var dataNew = dataOld.push(value);
Set the input data to new data:
$('#selectPretty').val(dataNew);
*This assumes that val() returns an array
Docs

Related

How to retain a value of dropdown using JS?

I have a three dropdown with 1 submit button. Now, I'm trying to retain the value of each dropdown after the user clicked the input submit. But the Jquery I have is not working. I use PHP to displayed the output of the dropdown when the user clicked it.
Note: The page is refresh when the user clicked the input submit.
How to fix this? See in plunker
JS:
$(document).ready(function(){
$('#dropdown').change(function(){
var option = $(this).find('option:selected').val();
$('#dropdown').val(option);
});
});
Use local storage with all option;
$("#dropdown").change(function(){
var html=$("#dropdown").html();
localStorage.setItem("myapp-selectval",html);
localStorage.setItem("myapp-selectvalselected",$("#dropdown").val()); //to retain selected value
})
Now on document load;
window.onload=function()
{
if(localStorage.getItem("myapp-selectval")!="" && localStorage.getItem("myapp-selectval")!=undefined)
{
$("#dropdown").html(localStorage.getItem("myapp-selectval"));
$("#dropdown").val(localStorage.getItem("myapp-selectvalselected")); //to get previously selected value
}
}
Once again as I said in comment it's not a good solution.
You can get the values easily by making use of the model attribute present in the select element.
First add a onclick function like so
<input type="submit" name="submit" value="Submit" onclick="getValues()"/>
Then get the value on submit of the button(Entire code) Plunkr
I had a look at your code, the way your selectbox rendering is setup we have to explicitly call the updateSelect() function for the options to work well. This function makes your selectbox "dynamic".
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
if(first !== null && second !== null && third !== null) {
setValues(); //this should come after getting the values above
}
function getValues() {
var first = document.getElementsByTagName("SELECT")[0].getAttribute("model");
var second = document.getElementsByTagName("SELECT")[1].getAttribute("model");
var third = document.getElementsByTagName("SELECT")[2].getAttribute("model");
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
}
//on load when this function is called globally, the values from the localStorage will be set to the dropdown values.
function setValues() {
//for first dropdown
document.getElementsByTagName("SELECT")[0].setAttribute("model", first);
document.getElementsByTagName("SELECT")[0].value = first;
updateSelect(document.getElementsByTagName("SELECT")[0]);
//for second dropdown
document.getElementsByTagName("SELECT")[1].setAttribute("model", second);
document.getElementsByTagName("SELECT")[1].value = second;
updateSelect(document.getElementsByTagName("SELECT")[1]);
//for third dropdown
document.getElementsByTagName("SELECT")[2].setAttribute("model", third);
document.getElementsByTagName("SELECT")[2].value = third;
updateSelect(document.getElementsByTagName("SELECT")[1]);
}
To retain the value you have no choice but to use a window.localStorage like so -
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
Then fetch the value
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
If the user is going to refresh the page, your best bet is to have the server send down the value that the user just submitted with the new page load.
If that's impossible for some reason, you can use localStorage:
$(document).ready(function(){
var prevVal = localStorage.getItem('selectValue');
prevVal && $('#dropdown').val(prevVal);
$('#dropdown').change(function(){
var option = $(this).val();
localStorage.setItem('selectValue', option);
});
});
Keep in mind that not all browsers support this API yet.
EDIT: If you don't need the browser to refresh, you can use Ajax:
// ...
$('#myForm').submit(function (event) {
event.preventDefault();
var option = $('#dropdown').val();
var fd = new FormData();
fd.append('dropdown', option);
$.ajax('/path/to/form/target/', {
method: 'POST',
formData: fd
});
// ...
});
//...
Although I assume OP's question asks for a JS solution, I do want to bring something else to the table because I was also searching to solve the same problem. However, I ended up solving it in a manner that I considered to be satisfying.
In my case I'm using Flask as the backend, but I believe the solution should be at least similar for other use cases.
On the HTML where the dropdown is located, I pass a variable from the backend which is originally set to be some default value of my choice. Let's call this variable default_var_set_in_backend. This will ultimately be fed to the HTML and will look like as follows:
<select name="some_name_you_want" onchange="this.form.submit()">
<option selected="selected">{{ default_var_set_in_backend }}</option>
Once a change is made in the dropdown value by the user (in my case it's a GET request), I update the variable default_var_set_in_backend to be equal to this new choice. Now, the HTML will reflect the latest choice made by the user once the page refreshes.

Pass hidden value in webpage using jqGrid javascript to server code on record insert

I want to insert a new record in the jqGrid with a default field (hidden) as a parameter to the controller. I was able to pass the parameter for the grid get query request by using
datatype: 'json',
postData: {
parameter_to_pass: function () { return document.getElementById('the_hidden_field').value; }
},
but I can't get the create new record to work.
Thanks in advance!
If you use form editing the you can extend the data, which will be send during Add operation, by usage of onclickSubmit callback:
$("#grid").jqGrid("navGrid", "#pager", {},
{}, // edit options
{ // add options
onclickSubmit: function () {
return {
parameter_to_pass: $("#the_hidden_field").val()
};
}
}
);
OK, not much to go on. Can you try breaking it up a bit, see where the problem is coming in? Try setting a variable to the contents of the hidden field and see if you can get the text out of the page for starters. You could also view the source to check that the hidden field is holding the value you think it is.
var hf = document.getElementById('the_hidden_field');
var hfvalue = hf.value;

Ajax/Jquery drop down menu, Javascript to get variable, variable is then used in PHP. Can't get it to work?

I am using Ajax/Jquery to display a dropdown menu with results from my SQL database. I'm using javascript to get a variable and then that variable is used within PHP. However it does not work.
I used Jquery .val() to get the variable from a select html tag when the user clicks the choices available.
Then, .on() to execute some php code depending on what the selected value from the dropdown box is.
My scenario is I have car classes (Sports, Hatchback) and cars available. What I am trying to do is, put the car classes in a dropdown box and then display the cars available dependent upon what the user has selected. I'm trying to do this using the above methods. (All this information is taken from a SQL database).
Has anyone got any solutions?
This is my my javascript code here:
<script>
var carid = $("#carid").val();
$("select[name='carid']").on("select",function(){$.post( "sDn.php", x, function( data ) { $( ".availablecar" ).append( data );});});
</script>
You probably want something like this
JavaScript
$("select[name='carid']").on("change", function() {
$.post(
"sDn.php",
{ carId: $("#carid").val() },
function(data) {
$(".availablecar").append(data);
}
);
});
PHP
$carId = $_POST['carId'];
You need to send the car id in the request and you probably need to bind to the change event, not select
You also need to get the car id value when the id has been changed, otherwise it will always remain the same value and never get updated when you change it
It appears to me that you are not using the carid variable anywhere. I think you mean to use carid instead of x
<script>
var carid = $("#carid").val();
$("select[name='carid']").on("select",function(){$.post( "sDn.php", carid, function( data ) { $( ".availablecar" ).append( data );});});
</script>
Also I would suggest parsing you form input if you don't already on the php side.
Try this:
$("#carid").on("change",function(e){
e.preventDefault();
var value = $(this).find("option:selected").val();
var $avaliable = $( ".availablecar" );
$.ajax({
url:'sDn.php',
type:'post',
data:{
'carid':value
},
dataType:'html',
success:function(result){
$avaliable.append( result );
}
});
});
Changed the $.post to $.ajax, passing the 'cardid' value.
Getting the selected option, on 'change'.

Translating ajax output with jQuery

I'm trying to translate some phrases with jQuery. This code mostly works great:
changeText = function(text, newText){
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(text,newText)); };
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 0000);
However, it's mostly useless when you wait for ajax generated results. To clarify - this is a search script with the following procedure:
When you click Search, you get a part of the page loaded "normally". I can change these text strings without any problems.
Afterwards there are results loaded dynamically through ajax I guess and there are div "blocks" getting loaded one after another. These phrases don't get translated.
A workaround is to wait for some time until everything gets loaded and then it does work for some parts. E. g.:
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 20000);
However, that's not a good solution, because users see untranslated strings that way for some time.
Therefore, I'm looking for a solution that would change strings as they get displayed. Is there a way to do that?
Thanks in advance!
EDIT:
Trying charlie's approach:
<script>
changeText = function(text, newText, $el) {
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
$(function(){
changeText(text, newText,$('span.example'));
});
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText(text, newText,$changeEl);
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(TranslateMe,Translation));
};
})
})
</script>
Your best/cleanest approach would be to add a callback from where the AJAX Call is being made and the content has been inserted in the divs.
If that is not possible for you there might be a possibility for you to get a callback if the DOM changes as asked here and here
I agree with Tyron that if you can, you should add or modify the callback function to the AJAX calls.
as for detecting the changes and translating without access to the ajax. something like this might help.
var c = document.getElementById('[ID OF CONTAINER FOR UNTRANSLATED BLOCKS]');
c.__appendChild = c.appendChild;
//this function catches the element before it is appended
c.appendChild = function(){
//this applies the change
c.__appendChild.apply(c, arguments);
var newBlock = $(c).children().last();
//this hides the newly added block
newBlock.hide();
// now perform your translations on the newBlock contents
//here
// and then make the block visible again
newBlock.show();
};
If you change the function to add a context argument you could do something like:
changeText = function(text, newText, $el) {
/* html method allows for function as argument to modify element*/
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
Then on page load:
$(function(){
changeText( text, newText,$('span.example'));
});
And in AJAX success look for the new elements and modify them:
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText( text, newText,$changeEl);
/* your code that inserts the new html here*/
})
})

How To Keep a JavaScript Working with ResonseText Data

I've been building an application with PHP/MySQL and JavaScript with Prototype/Scriptaculous.
A page has a search contacts field, with a default set of data in an HTML table. A user types in some characters, and the table get updated.
What's actually happening is the table is getting replaced with a new table and new data.
I've got a JavaScript that works against that table, which is loaded in the standard fashion via script tags at the bottom of the page.
Problem is, it only works on the default data (the part that's loaded with the page), when the search updates the table data, the script stops working. The search still will work since that was originally loaded with the page but it seems my script is unaware of page updates or new data.
How can I get this to work? Do I have to include the script with every Ajax call?
Thanks
Rich
Posting the relevant code would help, but you have most likely attached an event listener to an element that is replaced by the AJAX call.
If that is the case, you will need to recreate and reattach the event handler to the new element, even if that new element is exactly equivalent to the element it is replacing.
OK, I'll post a bit of code here.
But yes an event listener is attached to an element.
Here's a bit of the JavaScript class I was building which looks for events from a search field, collects data from that field and other form elements and sets them up in this.params.
After the data is returned to the AJAX object, it's updated to the page, which is identical to the original code (different rows).
var Compass_Search = Class.create({ ...
search: function() {
$('search_form').observe('change', this.get_data.bind(this));
},
get_data: function(e) {
var ele = e.target;
var filters = $$('.search_option');
if($(ele).tagName == 'INPUT') {
if($(ele).readAttribute('type') == 'checkbox') {
this.watch_filters(filters);
}
}
if(this.default_text == $('search_box').value) {
this.set_text_value('null');
} else {
this.set_text_value($('search_box').value);
}
new Ajax.Request(this.url, {
method: 'post',
parameters: this.params,
onComplete: function(r) {
result_text = r.responseText;
$('main').update(result_text);
}
});
},
...});

Categories

Resources