Wordpress Back-end Javascript Error - javascript

I've created a Custom Admin page on wordpress back-end, and have this basic html structure,
<ul data-status="available">
<li class="available">AVAILABLE</li>
<li class="onleave">ONLEAVE</li>
</ul>
When I use js code below, it works fine
$('ul').each( function() {
var status = 'available';
$(this).find('li.' + status ).addClass('active');
});
While this code below also works (it adds class on element), However it, produces an error
$('ul').each( function() {
var status = $(this).data('status');
$(this).find('li.' + status ).addClass('active');
});
Error on Console
Syntax error, unrecognized expression: li. load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=4.4.1:2
(9 Errors) Cannot read property 'hasClass' of undefined load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,svg-painter,heartbeat,wp-auth-check,thickb…:246
Any clear explanation would be highly appreciated
FULL JS CODE
( function($) {
'use strict';
$(document).ready( function() {
$('ul').each( function() {
var status = $(this).attr('name');
//$(this).find('li.' + status ).addClass('active');
});
$('form').on('click', 'li', function() {
var currentStatus = $(this).parent().attr('name');
var id = $(this).parent().attr('id');
var status = $(this).attr('name');
var input = '<input id="model-'+id+'" type="hidden" name="'+id+'" value="'+status+'" />'
if( currentStatus !== status || !currentStatus ) {
$('form').prepend( input );
} else {
$('form').find('#model-'+id).remove();
}
$(this).parent().find('li').removeClass('active');
$(this).addClass('active');
});
$('form').submit( function(e) {
e.preventDefault();
console.log( $( this ).serialize() );
});
});
})(jQuery);

A quick (although not very nice solution) would be to check the value/type of status and jump out of the .each() loop if it is not defined:
$('ul').each( function() {
var status = $(this).attr('name');
if (typeof status === "undefined" || !status) {
return false;
};
$(this).find('li.' + status ).addClass('active');
});
As I mentioned it is generally a bad idea to loop through ALL elements of a type on a page. It would be better to loop through a set of elements with a given class.

Try with this:
$('ul').each( function() {
var status = $(this).attr('data-status'); //note: data-status, not status
$(this).find('li.' + status ).addClass('active');
});
.data() method is for setting/getting object level data not represented visually in the Dom. You, however, are using attributes, which has a different accessor in jQuery (.attr()).
See here:
https://api.jquery.com/data/
and here
http://api.jquery.com/attr/

Related

Dynamic dropdowns filtering options with jquery

I am trying to filter one dropdown from the selection of another in a Rails 4 app with jquery. As of now, I have:
$(document).ready(function(){
$('#task_id').change(function (){
var subtasks = $('#subtask_id').html(); //works
var tasks = $(this).find(:selected).text(); //works
var options = $(subtasks).filter("optgroup[label ='#{task}']").html(); // returns undefined in console.log
if(options != '')
$('#subtask_id').html(options);
else
$('#subtask_id').empty();
});
});
The task list is a regular collection_select and the subtask list is a grouped_collection_select. Both which work as expected. The problem is that even with this code listed above I can't get the correct subtasks to display for the selected task.
NOTE: I also tried var tasks=$(this).find(:selected).val() that return the correct number but the options filtering still didn't work.
Try something like this instead (untested but should work).
$(function () {
var $parent = $('#task_id'),
$child = $('#subtask_id'),
$cloned = $child.clone().css('display', 'none');
function getParentOption() {
return $parent.find('option:selected');
}
function updateChildOptions($options) {
$child.empty();
$child.append($options);
}
$parent.change(function (e) {
var $option = getParentOption();
var label = $option.prop('value'); // could use $option.text() instead for your case
var $options = $cloned.find('optgroup[label="' + label + '"]');
updateChildOptions($options);
});
});

Syntax Error escaping characters

I'm getting SyntaxError: missing ) after argument list but I don't know what's wrong.
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); /**PROBLEM**/
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$('.btn-file :file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
Thanks for your help.
My objective was to style a bootstrap's input filetype so I tried to set a script like that (not working for me on localhost / MAMP) for showing file names and nr, once uploaded.
In my research I've found this bootstrap's script that do the job. It's a workaround but could help future visitors.

Class not changing after get request Jquery

I'm having trouble changing the class after making a jquery get request.
code:
<script>
//global variable
var table = []
var numberofaccounts = 0
$(document).ready(function() {
$('#form1').validate();
// add numbers to select ids
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
$('#apply_btn').click(function() {
table = []
var count = 0;
var text = "";
var tracker = 0
$('#stats_table tr').each(function(){
count = 0;
text = "";
$(this).find('td').each(function(){
count++;
if (count == 4) {
text += $( ".select_class"+ tracker + " option:selected" ).val();
} else {
text += " " + $(this).text() + " ";
}
})
table.push(text);
tracker++;
});
$.post("/apply_changes", {"data": JSON.stringify(table)}, function(data) {
var res = JSON.parse(data);
if (res.data == true){
$('#updated').text("Update Successful").css('color', 'green');
$.get("/", function( data ) {
$('#stats_table').load("/ #stats_table");
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
} else {
$('#updated').text("Update Unsuccessful").css('color', 'red');
}
});
});
});
</script>
So when the page first loads this method changes the class on dynamically created select elements.
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
After I make a post to flask the if the response data is true I go ahead and make a get request to grab the updated items from the db. I then refresh the table. This works great if I make one request. However on the second post nothing happens. This is because the classes that I modified at the start of the page load no longer exist. So i added the method above to also trigger after the get response (I also tried at the end of the post response). The problem is that the method doesn't seem to run again. The classes aren't there and as a result when I go to make another post request it can't find the element. How do I go about fixing this?
Things to note: The get request is necessary, the ids and classes cannot be statically assigned.
You are trying to assign classes before you even refresh your table.
$('#stats_table').load("/ #stats_table"); is called asynchronously and returns before it even completes.
You need to put you code, for assigning classes, inside the complete callback of your .load() call:
$('#stats_table').load("/ #stats_table", function() {
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});

To check that value in a textbox is inputted only from autocomplete values.

I am Developing a web application. For inputting values i am using an auto complete which gets its data from the database.
$(document).ready(function hello(){
var myVar1 = <%=request.getAttribute("variable1")%>
$("input#assignedbyid").autocomplete({
source: myVar1
});
});
The above given example gives me a set of values which are picked up from a database using JDBC and json code. AT any point of time the value in myvar1 looks like this::
["Kapil","Mayur","Abhinav","Chandan"]
Which comes as a source for auto complete values.
My html code where my input tag onfocus calls up the function hello().
<div id="lets"><input dojoType="dijit.form.ValidationTextBox" id="assignedbyid" name="assignedbyname" required="true" onfocus="hello();" onblur="hi();"></div>
Now i want to have a validation check which checks that value entered by the user comes from auto complete values only("Kapil","Mayur","Abhinav","Chandan") and not any other value. I have this Code where in if no value is entered the text box shakes up(onblur="hi();"). in else part i want to that checking to be done.
<script type="text/javascript">
function periodical() {
$('#lets').effect('shake', { times: 5 }, 200);
};
$(document).ready(function() {
$('#lets').hide().css('display','').fadeIn(600);
});
function hi(){
var dude = dojo.byId("assignedbyid").value;
if(dude==""){
periodical();}
else{
if(dude)
myVar1
alert("value entered");}
};
</script>
My else part is incomplete for the time being. how can this be done ?. Thanks .
If you're using jQuery, you can use the $.inArray() method:
if($.inArray(enteredValue, myArray) == false) { ... } // If enteredValue is not in myArray
If you're just using plain Javascript, it is also simple:
if(myArray.indexOf(enteredValue) == -1) { ... } // If enteredValue is not in myArray
var V = $("#myInput").val();
if (V=="Kapil"||V=="Mayur"||V=="Abhinav"||V=="Chandan") {
//do something
}
or
var V = $("#myInput").val();
var myArray = ["Kapil","Mayur","Abhinav","Chandan"];
if ($.inArray(V, myArray)!=-1) {
//do something
}
Use this sample code for your autocomplete.
sample code..
var url1 = sitepath+'opportunity/contact_autocomplete/';
var related= '';
$(function() {
$( "#txtcontactid" ).autocomplete(
{
source:url1,
select: function( event, ui )
{
log(
ui.item.id
);
}
});
});

How to get jQuery placeholder/watermark plugin to work for ajax loaded text fields?

I'm using the following placeholder plugin
(function($){
var ph = "PLACEHOLDER-INPUT";
var phl = "PLACEHOLDER-LABEL";
var boundEvents = false;
var default_options = {
labelClass: 'placeholder'
};
//check for native support for placeholder attribute, if so stub methods and return
var input = document.createElement("input");
if ('placeholder' in input) {
$.fn.placeholder = $.fn.unplaceholder = function(){}; //empty function
delete input; //cleanup IE memory
return;
};
delete input;
//bind to resize to fix placeholders when the page resizes (fields are hidden/displayed, which can change positioning).
$(window).resize(checkResize);
$.fn.placeholder = function(options) {
bindEvents();
var opts = $.extend(default_options, options)
this.each(function(){
var rnd=Math.random().toString(32).replace(/\./,'')
,input=$(this)
,label=$('<label style="position:absolute;display:none;top:0;left:0;"></label>');
if (!input.attr('placeholder') || input.data(ph) === ph) return; //already watermarked
//make sure the input tag has an ID assigned, if not, assign one.
if (!input.attr('id')) input.attr('id', 'input_' + rnd);
label .attr('id',input.attr('id') + "_placeholder")
.data(ph, '#' + input.attr('id')) //reference to the input tag
.attr('for',input.attr('id'))
.addClass(opts.labelClass)
.addClass(opts.labelClass + '-for-' + this.tagName.toLowerCase()) //ex: watermark-for-textarea
.addClass(phl)
.text(input.attr('placeholder'));
input
.data(phl, '#' + label.attr('id')) //set a reference to the label
.data(ph,ph) //set that the field is watermarked
.addClass(ph) //add the watermark class
.after(label) //add the label field to the page
//setup overlay
itemFocus.call(this);
itemBlur.call(this);
});
};
$.fn.unplaceholder = function(){
this.each(function(){
var input=$(this),
label=$(input.data(phl));
if (input.data(ph) !== ph) return;
label.remove();
input.removeData(ph).removeData(phl).removeClass(ph).unbind('change',itemChange);
});
};
function bindEvents() {
if (boundEvents) return;
//prepare live bindings if not already done.
$("form").live('reset', function(){
$(this).find('.' + ph).each(itemBlur);
});
$('.' + ph)
.live('keydown',itemFocus)
.live('mousedown',itemFocus)
.live('mouseup',itemFocus)
.live('mouseclick',itemFocus)
.live('focus',itemFocus)
.live('focusin',itemFocus)
.live('blur',itemBlur)
.live('focusout',itemBlur)
.live('change',itemChange);
;
$('.' + phl)
.live('click', function() { $($(this).data(ph)).focus(); })
.live('mouseup', function() { $($(this).data(ph)).focus(); });
bound = true;
boundEvents = true;
};
function itemChange() {
var input = $(this);
if (!!input.val()) {
$(input.data(phl)).hide();
return;
}
if (input.data(ph+'FOCUSED') != 1) {
showPHL(input);
}
}
function itemFocus() {
$($(this).data(ph+'FOCUSED',1).data(phl)).hide();
};
function itemBlur() {
var that = this;
showPHL($(this).removeData(ph+'FOCUSED'));
//use timeout to let other validators/formatters directly bound to blur/focusout work
setTimeout(function(){
var input = $(that);
//if the item wasn't refocused, test the item
if (input.data(ph+'FOCUSED') != 1) {
showPHL(input);
}
}, 200);
};
function showPHL(input, forced) {
var label = $(input.data(phl));
//if not already shown, and needs to be, show it.
if ((forced || label.css('display') == 'none') && !input.val())
label
.text(input.attr('placeholder'))
.css('top', input.position().top + 'px')
.css('left', input.position().left + 'px')
.css('display', 'block');
//console.dir({ 'input': { 'id':input.attr('id'), 'pos': input.position() }});
}
var cr;
function checkResize() {
if (cr) window.clearTimeout(cr);
cr = window.setTimeout(checkResize2, 50);
}
function checkResize2() {
$('.' + ph).each(function(){
var input = $(this);
var focused = $(this).data(ph+'FOCUSED');
if (!focused) showPHL(input, true);
});
}
}(jQuery));
It applies the placeholder attribute to form fields in browsers that do not natively support the placeholder attribute (ex. IE9). It works for statically loaded text fields, however for text fields that are loaded via ajax, the placeholder does not appear.
Is it possible to achieve this 'watermark' effect on text fields that are loaded via ajax?
What happens if you trigger the window resize function after adding in new inputs?
$(window).trigger('resize')
You could apply the plugin to newly created controls after the AJAX call completes. Forgive the pseudo-code as I'm not really sure about how your AJAX calls are working:
$.ajax({
url: "test.html",
cache: false
}).done(function( result ) {
field = $('<input>').html(result);
$("#results").append(field);
field.placeholder();
});
Another option is that you could use jQuery's .on() method to bind dynamically created controls to the function--but it wants an event (like click). I'm not sure how you would do that. Maybe something like this:
$( 'body' ).on('click','input.addField', function(e){
$(this).placeholder();
});
I know this won't work, but maybe it helps get you brainstorm solutions.

Categories