Jquery. Binding the instantiation of a plugin on dynamically loaded content - javascript

Having a problem selecting an id within a dynamically placed div tag on a page.
It's a date field and I'd like to have a datepicker show up when the user focuses on the field. That I'm trying to set up a plugin instead of doing any other kind of jQuery event is, I think, my problem.
So here's the dynamically loaded content that is placed on the page when a user clicks one of several radio buttons in a "calendar".
$("#s10").click(function(){
$("#S_Date").html('<input type="text" name="Start_Date" id="Start_Date" value="2016-05-24" />2016-05-24');
#S_Date is the parent div id that is loaded when the document loads.
I'm using the "PickMeUp" datepicker plugin.
From what I can tell, I need to use the on() event handler but I just can't seem to get it to bind to #Start_Date.
Here's my latest attempt at trying to call it:
var pickitup = $("#Start_Date").pickmeup({format : 'Y-m-d'});
$("#S_Date").on('focus', "#Start_Date", function(){pickitup});
With pickitup defined, I have also tried:
$("#S_Date").on('focus', "#Start_Date", pickitup);
$("#S_Date").on('focus', "#Start_Date", function(){pickmeup({format : 'Y-m-d'})}); fails out of the gate with a pickmeup is not defined error.
Ideas anyone?

So, if I'm understanding what you're doing, you want to insert some html into a given element on that click event, then apply the date picker functionality to it?
$("#s10").on("click", function() { //when the element is clicked...
//create an input with the appropriate attributes
var picker = $("<input />", { type: "text", name: "Start_Date", value: "2016-05-24" });
//append it to the desired element(s)
$("#S_Date").append(picker);
//run the plugin on it
picker.pickmeup({format: 'Y-m-d'});
});
Here's a working (simple) fiddle https://jsfiddle.net/s6vu0rnq/
The undefined error you got was because "pickmeup" is a property of jquery's prototype, but you were trying to call it from the global scope.
Also, ".click" is just an alias for ".on", so you can use either.

Related

The use of JavaScript onchange("<function>(this.id)") on c# CheckBox vs other c# Controls

I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.

With select2, how to access the original select/input element after it's been processed?

I'm using a combination of JQuery EasyUI and Select2 to be able to drag options from a right panel, onto a left select box.
In the original HTML, the select boxes are empty, and I only "add" anything to them if I drop an option on them,
<form id="section1">
<select class="select2" class="drop_target" id="selected_options" name="selected_options"></select>
<div>
<div class="draggable_option" data-id="1234">1234</div>
</div>
</form>
<form id="section2">
<select class="select2" class="drop_target"></select>
<div>
<div class="draggable_option" data-id="1235" id="selected_options" name="selected_options">1235</div>
</div>
</form>
Then in javascript, I do something like this,
$('.drop_target').droppable({
accept: '.draggable_option',
onDrop:function(e, source){
var $dragged_source = $(source);
var $drop_target = $(this);
}
});
The problem comes at this point, if you're dynamically adding things to the select, you have to check it doesn't exist, and if it doesn't, you create a new option, and add it,
var new_option = {
id: $drag_source.data('id'), data_id: $drag_source.data('id'),
text: $drag_source.val(), selected: true};
// Set the value, creating a new option if necessary
if (!$drop_target.find("option[value='" + new_option.id + "']").length) {
// Append it to the select
$drop_target.append(new Option(
new_option.text, new_option.id, true, true)).trigger('change');
}
var data = $drop_target.select2('data');
$drop_target.select2('data', data.concat([new_option]));
Clear as mud? Unfortunately it goes wrong at this point. While all calls to .select2 from $drop_target work as expected, this is not the select that was originally in the HTML, this is a div that select2 created, after hiding the original select, with an id attribute like id="s2id_selected_options". So when we append the new option to it, it doesn't get added to the select, and gets added to select2's div incorrectly instead.
My HTML pseudocode is deliberately set up in this "obtuse" way, because my page is like that. I have multiple forms, and multiple "identical" selects in those forms, generated by WTForms. So the "general" method of selecting your select by id, $('#selected_options') doesn't work correctly.
What I need to do, within the javascript, is gain access directly to the original, now hidden, select, and I can't access it via id.
When you have access to one of the elements that's "associated" with the generated by select2, you can access meta information for it via .data('select2'), or in this instance,
$(this).data('select2');
In here, there's loads of metadata that select2 uses (which you can see if you browse the source). For this question, to get the original select or input element, you can use,
var $drop_target = $(this).data('select2').opts.element;
Whether you're using a select, or an input, this gives you a jQuery element linking to it. If you're using a select, and are only interested in that, you can use the shorter option,
var $drop_target = $(this).data('select2').select;
This may be in the docs somewhere, but I was unable to find it, and I'm also not able to find it by searching now, because searching the docs for "data" and "select2" returns a result for nearly every page of their docs (hence the reason I'm answering this question myself, to hopefully save others the trouble).

jQuery: show html elements when a disabled select menu is loaded

In my application users can edit information for their reservation but I don't want them to change the type of reservation. So I have thought to load a page with a select menu displaying the type of reservation but it is also disabled. What I would like to happen is that on page load if the select menu is disabled then the relative elements are showed according to the selected but disabled type. Reading the documentation this is what I have thought I need:
jQuery("#tipologia_piazzola").load(function(){
alert("something");
if (this.value == "mensile" && this.is(":disabled")) {
jQuery(".both").show();
jQuery(".mensile").show();
jQuery(".giornaliera").hide();
}
});
Obviously I have inserted it inside the ready function but neither the alert nor the html elements appear. Is this the correct way? Or, how can I reach my goal?
You need to use jQuery(this) instead of this to call is(':disabled') function because it need jQuery object and not javascript object. Also use document.ready as shown below to ensure that all DOM element is ready.
jQuery(document).ready(function(){
var $this = jQuery('#tipologia_piazzola');
if ($this.val() == "mensile" && $this.is(":disabled")) {
jQuery(".both").show();
jQuery(".mensile").show();
jQuery(".giornaliera").hide();
}
});
NOTE : - please exclude document.ready if you have it already and put above code in your existing document.ready

Change Text Field Once Drop Down Has Been Selected (Multiple forms on 1 page)

I'm looking to change the value of a <p> tag once an option from a drop down has been selected. I have that working but my issue is I am going to have lots of forms on one page and feel like I am repeating my code. Is there a way to do this with a function for example? To save me writing a new section of javascript everytime a form gets added to my page?
My javascript code:
$('.orderProduct select#packageOption').change(function(){
$('#packagePrice').html($(this).val());
});
$('.orderProduct2 select#packageOption').change(function(){
$('#packagePrice2').html($(this).val());
});
Thanks.
Add a data-element-id attribute to each select like:
<select data-element-id="packagePrice">...</select>
<select data-element-id="packagePrice2">...</select>
then you simply need this jQuery code:
$('select[data-element-id]').change(function(){
var $this = $(this);
var id = $this.data('element-id');
$('#' + id).html($this.val());
});
If you want to avoid the extra attribute you could use jQuery's DOM traversing functions, to locate which p you should update.

How to get a form elements value in the resulting child window (jQuery)

I'm trying to pass the value of an input element from a form on my parent page to its child page. The form element on my opener page, as follows:
<input id="selectedOrgName" type="text" value="SOME_VALUE" name="selected_org_name">
The value of "SOME_VALUE" is dynamic and needs to be passed onto the child page. What I need to do is find that value by referencing the opener's input value.
I've tried a few things, mostly with basic JavaScript and have been unsuccessful -- so, I thought I'd try jQuery, but that is not working either. The code I've tried:
var abc = openerF.$("[name=selectedOrgName]");
Just do :
var selectedOrgNameValue = $("#selectedOrgName", window.opener.document).val();
Note that if you dont want / need to load jQuery in the child window, you can do :
var selectedOrgNameValue = window.opener.jQuery("#selectedOrgName").val();

Categories