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

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

Related

How to select for multiple fields with Jquery?

I currently have a form that is displaying fields that I do not want it to. There are 3 input fields associated with one form and the same form is being rendered multiple times.
I have my template set up to check for when this was only one value. I need to change it so the template will check for all of the values present & then decide to render.
So for example,
I have,
Div_id_form-0-x,
Div_id_form-0-y,
Div_id_form-0-z,
Div_id_form-0-location__location_category__requires_coordinates
What selector can I use to grab all of these to use in my template?
I need to grab them for each form. Where it says form-0 I have several of these forms repeating.
Then in HTML I have something like this.
$(function () {
// Determine weather we are in a modal window.
var context = $("#{{ contextId }}-form");
console.log("this is the {{ contextId }}" )
// Show required coordinates if location category requires them.
context.find("#id_location__location_category__requires_coordinates").change(function () {
if (context.find("#id_location__location_category__requires_coordinates").val() == 'Y') {
context.find('#id_needs_coordinates').removeClass('hide');
} else {
context.find('#id_needs_coordinates').addClass('hide');
}
});
});
Right now this is only checking for one value to determine whether to hide. I need it to check all of these for this value. Which is why I'm looking for a Jquery selector that can do such.
If you want a selector for IDs, you can use:
$("#Div_id_form-0-x, #Div_id_form-0-y, #Div_id_form-0-z, #Div_id_form-0-location__location_category__requires_coordinates")
Please see: https://api.jquery.com/id-selector/
Update
In the future, please clarify the entire issue and provide a proper example.
You can use the Attribute selectors.
$("[id^='Div_id_form-']")
This will select all IDs like:
Div_id_form-0-x
Div_id_form-1-x
Div_id_form-2-x
You will then select all of those elements.
See More: https://api.jquery.com/category/selectors/attribute-selectors/

Dynamically loaded JS needs to be clickable just like it's in the html

My page fires off an ajax query, where the MySQL Db is queried and the results are returned. (all successful).
Those results are formatted for output as a shopping gallery/catalogue and also as an accordion filter menu. So I can filter the shopping catalogue display. eg say I want to see only items that are red.
All is working so far.
My problem is with the filter accordion menu - dynamically created in js.
When I click on any selectable item in the tab-content, nothing happens. This means the parameter that should be sent, isn't being sent.
If I hard code the accordion filter or even load it with my server-side language, into the html directly, the filtering does send off the parameter and so the shopping catalogue is adjusted accordingly but, in that scenario, I am unable to dynamically change the filter menu.
I think the code I shall post below is the relevant code that recognises changes in the originally loaded content and fires off the ajax but (I think) it doesn't understand any changes to textboxes in the dynamically loaded content.
Please help me to understand what I need to add that will make dynamically loaded content fire-off to the ajax calls.
var $checkboxes = $("input:checkbox");
function update_nav_filter(opts) {
$.ajax({
type: "POST",
url: "/php-queries/product-filter-query.php",
dataType: 'json',
cache: false,
data: {
filterOpts: opts
},
success: function(records) {
//console.log(records);
//alert('SUCCESS!');
// alert(records);
$('#filters_div').html(makeFilter(records));
}
});
}
$checkboxes.on("change", function() {
//alert('there is a change is checkbox status'); // working on page load but not when any checkbox is clicked-on
var opts = getCatalogueFilterOptions();
updateCatalogue(opts);
update_nav_filter(opts);
});
$checkboxes.trigger("change");
Any help greatly appreciated.
I have created an event listener.
Following page-load, I select an item in the JS generated nav filter. eg pedal_bins in the sub_category section. I am then shown a display of pedal_bins. :)
Then I select 'kettles', another sub_category but I can only see the last sub_category that I click on. The pedal_bins disappear.
How best can I build and remove items with a single click? Store in a session parameter and then
a. remove the latest click if it matches whats in the session
b. add the latest click if its not already in the session
Then submit whatever the array is at that stage?
Or, is there a better way to run this?
Here's the listeneer
enter code here
document.getElementById("filtering_div").addEventListener("click",function(e) {
// e.target was the clicked element
if (e.target && e.target.matches("input")) {
var parameter = e.target.id;
//console.log("Anchor element", parameter , " was clicked" );
var opts = getCatalogueFilterOptions(parameter);
console.log(opts);
// update_nav_filter(opts);
updateCatalogue(opts);
}
});
You have a "delegation" problem. When you create a dynamic element, in order to be able to act on the newly created element, you have to reference it as a child element that was originally loaded with the DOM.
For example, if you have an element called <div id="top"></div> and you create a dynamic element, let's say <button id="test">Click</button> in there, you'll have to refer to that div when adding an event listener.
$("#top").on('click', '#test', function(){
//event related code goes here.
});
Here is a fiddle I created that explains the whole thing with some examples.
If you have any questions about it, please let me know.

Populate a div from TinyMCE content dynamically

I'm trying to get the contents from a TinyMCE textarea to populate a button/div as I type. This is to show the client how the button/div will look like when it goes live. Everything else works dynamically, such as the button/div colour, the title and dropdown.
The issue lies with dynamically retrieving the contents from TinyMCE. If I use a standard textarea box it works fine. I want the client to be able to use some of the basic features of TinyMCE.
Kind of how this form field is working. As I'm typing in this box, I can see my text updating below.
My JS is:
$(document).on('change', '#ParentID', function() {
var NTxt = $('#ParentID option:selected').text();
var NVal = document.getElementById("ParentID").value;
NTxt = NTxt.replace(/ # /g,"<br/>");
if(NVal != "0"){
if(NTxt.value != null || NTxt.value != "0" || NTxt.value != undefined){
$("#LTxt").html(NTxt);
}
}else{
$("#LTxt").html('External Link Text/Quote Text');
}
});
$(document).on('keyup', '#Opt2', function() {
$('#LTxt').text($(this).val());
});
Here are some screen grabs:
1. Normal State:
2. Populated title and dropdown "internal link" text:
3. Textarea, populating same place (WITHOUT TINYMCE):
Anyone know how I can do this with TinyMCE? I've tried...
tinymce.get('content id').getContent()
...but it didn't seem to populate dynamically.
This is the key question: How to pass anything typed into the TinyMCE textarea into the button, at the bottom, as the user is typing?
Many thanks in advance,
Glynn
You need to use a variety of events that TinyMCE triggers to know when its content has changed. You can then grab the content from the editor and do whatever you need with it.
Here is an example that shows the actual raw HTML in a neighboring DIV. It can easily be adapted to insert the HTML into an elements so its actually rendered to the page.
http://fiddle.tinymce.com/Gegaab/5
The list of available events is documented here: https://www.tinymce.com/docs/advanced/events/#editorevents
The example uses the keydown and change events in particular but there are many to choose from if those don't fit your needs.

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

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.

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

Categories