Jquery - Initialize Select Box after first use - javascript

Page is loaded with a hidden select box in it.
I click on a button
I append elements to this select box, I move it and I make it visible
I apply plugin Chosen on it
This is done by this function
function moveHiddenSelect(idOffline, type, idMedia, mediaName){
var $selToReplace = $("#"+type+"_"+idOffline);
var $selOriginal = $("#originalSelect");
$selToReplace.replaceWith($selOriginal);
$.getScript('/lib/chosen/chosen.jquery.min.js', function(){
$selOriginal.chosen(); //load plugin script and apply it on the select box
});
$selOriginal.css("width", "220px");
$selOriginal.css("visibility", "visible");
}
No problem when I click the button one time, but when I click again on the button (step 2) nothing is happend..

The chosen() should be called once, just for creation.
After updating the values of each dropdown, you could use: $(DropdoenElement).trigger("liszt:updated");
function moveHiddenSelect(idOffline, type, idMedia, mediaName){
var $selToReplace = $("#"+type+"_"+idOffline);
var $selOriginal = $("#originalSelect");
$selToReplace.replaceWith($selOriginal);
selOriginal.chosen(); // Init the plugin
$.getScript('/lib/chosen/chosen.jquery.min.js', function(){
//load plugin script and apply it on the select box
selOriginal.trigger("liszt:updated")
});
$selOriginal.css("width", "220px");
$selOriginal.css("visibility", "visible");
}
Hope it helps!

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');
};
});

show hide field depend on select value sharepoint online

I have a list of 2 columns, the first one is "City" which is choice type.the second column is "Other" which is a single line of text.
when the user chooses "other " in City I want "OtherCity "column appears, if he chooses another choice, I want to hide.
I write the code using simple javascript, I do not want to use any library just simple code in javascript.
<script type="text/javascript">
function mySelectfunction(){
getValue = document.getElementById("City").value;
if(getValue == "other"){
document.getElementById("OtherCity").style.display ="none";
}else{
document.getElementById("OtherCity").style.display ="block";
}
}
</script>
but it does not work. can you help make it work?
*another question: if the second column which I want to hide type is "lookup " will the code be different?
My test code for your reference,and Choice and lookup column do not need to change the code.
Add a script editor in NewForm,and insert the code into it(replace the column name).
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
<script src="https://xxxx.sharepoint.com/sites/dev/SiteAssets/sputility.js">
</script>
<script>
$(document).ready(function () {
// Get a single select dropdown field
var relacionField = SPUtility.GetSPField('CityLookUp');
// create a function to show or hide Rates based on Rate value
var showOrHideField = function() {
var relacionFieldValue = relacionField.GetValue();
// Hide the Rates field if the selected value is Especial
if(relacionFieldValue === 'other') {
SPUtility.ShowSPField('Other')
}
else {
SPUtility.HideSPField('Other')
}
};
// run at startup (for edit form)
showOrHideField();
// make sure if the user changes the value we handle it
$(relacionField.Dropdown).on('change', showOrHideField);
});
</script>
You can download sputility.js here: https://archive.codeplex.com/?p=sputility
Updated:
Did the code above report any error?
JavaScript code:
ExecuteOrDelayUntilScriptLoaded(show,"sp.js");
function show () {
//Get the select element corresponding to column
var selectElement=document.getElementById('CityLookUp').parentNode.parentNode.childNodes[3].childNodes[3].childNodes[0];//chnage coulmn name
//get tr the hidden column located
var trElement=document.getElementById('Other').parentNode.parentNode;//change column name
//hide tr when we get into page,if the default value is 'other' ,do not need this
trElement.style.display='none';
//select change event
selectElement.onchange = function () {
var index = selectElement.selectedIndex;
//get option value
var value = selectElement.options[index].text;
if(value==='other'){
//show tr element
trElement.style.display='';
}else{
//hide tr element
trElement.style.display='none';
}
}
}
The code idea is to find the corresponding select element and decide whether to hide the tr element where column other is located according to the value of option.
Tip: Our page dom structure may be different, so you may need to modify the code according to your page dom structure. You could view your page dom structure by Developer tool.
Test result:

Duplicate HTML in jQuery into a BootStrap Modal

The function below is called after an icon is clicked, which creates a modal. During the function, I traverse up the DOM, grab a HTML canvas and display it in the modal. The problem I am having is that it is removing the HTML I grab initially, I want it to be duplicated. Can anyone shed some light on this?
JS:
$('#chartModal').on('show.bs.modal', function (event) {
console.log('yeppp');
// Button that triggered the modal
const button = $(event.relatedTarget)
// Get corresponding chart's HTML
const chart = button.parent().next()[0]
var modal = $(this)
// Update modal's content with the corresponding chart
modal.find('.modal-body').html(chart)
})
Regards,
James.
Since you are using jQuery, you can use the .clone() method like so:
$('#chartModal').on('show.bs.modal', function (event) {
// Button that triggered the modal
var button = $(event.relatedTarget);
// Get corresponding chart's HTML
// "chart" is a plain node here
var chart = button.parent().next()[0];
var modal = $(this);
// Update modal's content with the corresponding chart
modal.find('.modal-body').html($(chart).clone());
})
// OR
$('#chartModal').on('show.bs.modal', function (event) {
// Button that triggered the modal
var button = $(event.relatedTarget);
// Get corresponding chart's HTML
// "chart" is now a jQuery object
var chart = button.parent().next();
var modal = $(this);
// Update modal's content with the corresponding chart
modal.find('.modal-body').html(chart.clone());
})
Your current code snippet seems overly complicated in my opinion.
Here's a different solution that might be easier to follow:
HTML:
...
<canvas class="one-of-my-charts"></canvas>
...
JS:
$('.one-of-my-charts').click(function(e) {
$('#the-chart-modal').html(e.target);
$('#the-chart-modal').modal('show');
});

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

Categories

Resources