Cannot read property 'split' of undefined - javascript

Im facing a problem here when im trying to split class attribute like that
<div class='message_holder user1212 chatid142'></div>
so from my function i want to get user id (1212) and chatid ( 142)
But im getting the error in my tittle
how can i fix that pls.
function user_chat_id(){
classList = $(this).attr("class").split(/\s+/); //----here im getting the error
$.each(classList, function(index, item) {
if (item.indexOf("user") > -1) {this_id = item;}
if (item.indexOf("chatid") > -1) {this_chat_id = item;}
});
this_id = this_id.replace('user', '');
this_chat_id = this_chat_id.replace('chatid', '');
return [this_id,this_chat_id];
}
Edit :
and when i call it
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id();
alert(this_id);
})

Why your code is not working.
$(this) will be current window. In that .attr("class") will be undefined. So when you try to split it will throw an error.
Demo for showing $(this) will be current window.
$(document).ready(function(){
$("p").click(function(){
a()
});
});
function a(){
console.log($(this))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>
Soluton
Pass the current element as an argument to the function.
Changes to be made
var this_id = user_chat_id($(this)); //While calling.
function user_chat_id(elem){ // in function definition
You should use elem instead of $(this)
Demo for showing how to pass the element with it
$(document).ready(function(){
$("p").click(function(){
a($(this))
});
});
function a(elem){
console.log(elem)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>

The problem with your current code is that the value of this in your function is undefined (if in strict mode) or set to the global context (if not in strict mode) because it's just a regular function call. So, $(this).attr("class") will just return undefined and then when you try to do .split() on it, you get the error you see.
I'd suggest a much cleaner implementation that uses a regex to get the numbers for you:
function getId(str, key) {
var regex = new RegExp("\\b" + key + "(\\d+)\\b");
var match = str.match(regex);
return match ? match[1] : null;
}
function user_chat_id(obj){
var classList = obj.className;
var userId = getId(classList, "user");
var chatId = getId(classList, "chatid");
return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id(this);
alert(this_id);
});
In addition, the HTML you show:
<div class='message_holder user1212 chatid142></div>
is missing a closing quote on the class attribute. It should be:
<div class='message_holder user1212 chatid142'></div>
Working demo:
function getId(str, key) {
var regex = new RegExp("\\b" + key + "(\\d+)\\b");
var match = str.match(regex);
return match ? match[1] : null;
}
function user_chat_id(obj){
var classList = obj.className;
var userId = getId(classList, "user");
var chatId = getId(classList, "chatid");
return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id(this);
alert(this_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='message_holder user1212 chatid142'>Put the mouse over this text</div>

Related

Javascript fires twice Wordpress admin metabox

I added a inline Javascript code to my metabox callback function.
add_action( 'add_meta_boxes', function() {
add_meta_box( 'catalog-item', 'Gegevens', 'catalog_details_callback', 'catalog', 'advanced' );
});
function catalog_details_callback( $post ) {
<input type="text" class="price" name="price" id="price"/>
<script type="text/javascript">
document.getElementById('price').onfocusout = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
</script>
}
If the function is triggered the function fires the alert twice.
Does anybody know how I fix this?
There could be multiple reason for this:
Please check if you have multiple event listeners. If so, try to check your condition. understand about event listeners here: https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event
onfocusout bubbles, means if you have any event written on parent as well as child then both gets called. try to add
document.getElementById('price').onfocusout = function(event) {
event.preventDefault();
event.stopPropagation();
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
If still issue persists then try to add the debugger in the function can check the call trace in google developers console.
I had the same issue with Wordpress.
This works for me
const price_field = document.getElementById('price');
price_field.addEventListener('focusout', (event) => {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(price_field.value) == false ) {
this.value = price_field.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = price_field.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
price_field.value = after;
alert(after);
});

Returning variable from jquery on select function to another jquery on click fucntion

I want to the value of paramValue from .change event function into var searchValue to be displayed together at .click event. console.log(paramDD) gives me "undefined".
$( '#userSearchParam' ).change(function paramDropDown(){
var paramValue = $(this).val();
console.log(paramValue);
return paramValue;
});
var paramDD = paramDropDown();
console.log(paramDD);
$('#userSearchBtn').click(function () {
var textBoxValue = $('#userSearchBox').val();
console.log(textBoxValue);
var searchValue = textBoxValue + paramDD;
console.log(searchValue);
});
Try this:
function paramDropDown(){
var paramValue = $('#userSearchParam').val();
console.log(paramValue);
return paramValue;
}
$( '#userSearchParam' ).change(paramDropDown);
var paramDD = paramDropDown();
console.log(paramDD);
I'm not sure exactly what you're trying to accomplish though. If you can let us know your use case maybe we can recommend a solution.

Failure in changing node content + JavaScript

I wrote this code for create menu with div tag
HTML:
<div id="firstMenuList">
<div id="firstMenu">chooseâ–¼</div>
<div id="menulist" class="menulist"></div>
</div>
JavaScript:
<script>
function ccc() {
var id="firstMenu";
var ar=new Array("hi","there","hello","world");
var node=document.createElement("div");
var parent=document.getElementById("menulist");
var nodeData="";
for (var i=0;i<ar.length;i++)
{
var node=document.createElement("div");
node.setAttribute("id",id+""+i);
node.setAttribute("class","menulist");
node.setAttribute("onclick","select("+id+""+i+")");
node.style.top=((i+1)*100)+3+"%";
node.innerHTML=ar[i];
parent.appendChild(node);
}
}
function select(id)
{
var p=document.getElementById(id);<-this doesn't work on elements that created dynamically
p.style.backgroundColor="red";
var t = p.innerHTML;
}
</script>
This code creates the menu, but when I click on the menu items code breaks.
The error is:
"parent is null"
To pass the id to the function you need to ensure that you put quotes around the id:
node.setAttribute("onclick","select('"+id+i+"')");
// note the single quotes ----------^--------^
Demo: http://jsfiddle.net/QK5Wh/1/
But you don't need to use the id to get the element when you can pass a direct reference to the element itself:
node.setAttribute("onclick","select(this)");
And then:
function select(p) {
p.style.backgroundColor="red";
var t = p.innerHTML;
}
Demo: http://jsfiddle.net/QK5Wh/
I'll suggest to avoid the inline event binding. Here is a working example:
http://jsfiddle.net/H4S2f/1/
function ccc() {
var id="firstMenu";
var cls="firstMenuList";
var ar=new Array("hi","there","hello","world");
var node=document.createElement("div");
var parent=document.getElementById("menulist");
var nodeData="";
for (var i=0;i<ar.length;i++)
{
var node=document.createElement("div");
node.setAttribute("id",id+""+i);
node.setAttribute("class","menulist");
(function(i) {
node.addEventListener("click", function() {
select(id+""+i)
});
})(i);
node.style.top=((i+1)*100)+3+"%";
node.innerHTML=ar[i];
parent.appendChild(node);
}
}
function select(id)
{
var p=document.getElementById(id);
p.style.backgroundColor="red";
var t = p.innerHTML;
}
ccc();

jQuery getting ID of clicked link

I have a modal box in jQuery which I have created to display some embed code. I want the script to take the id of the link that is clicked but I can't seem to get this working.
Does anyone know how I can do that or why this may be happening?
My jQuery code is:
function generateCode() {
var answerid = $('.openembed').attr('id');
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<code><iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '" frameborder="0"></iframe></code>');
}
$(document).ready(function () {
$('.openembed').click(function () {
generateCode();
var answerid = $('.openembed').attr('id');
$('#box').show();
return false;
});
$('#embed').click(function (e) {
e.stopPropagation()
});
$(document).click(function () {
$('#box').hide()
});
});
My mark-up is:
Embed
Embed
Your problem is here:
$('.openembed')
returns an array of matched elements. Your should instead select only the clicked element.
$('.openembed') works correctly if you assing a click event to all elements that have this class. But on the other hand, you're unable do know which is clicked.
But fortunately in the body of handler function click you could call $(this).
$(this) will return the current (and clicked element).
// var answerid = $('.openembed').attr('id'); // Wrong
var answerid = $(this).attr('id'); // Correct
// Now you can call generateCode
generateCode(answerid);
Another error is the body of generateCode function. Here you should pass the id of selected element. This is the correct implementation.
function generateCode(answerid) {
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '"frameborder="0"></iframe>');
}
Here I have implemented your code with the correct behavior: http://jsfiddle.net/pSZZF/2/
Instead of referencing the class, which will grab all members of that class, you need to reference $(this) so you can get that unique link when it is clicked.
var answerid = $(this).prop('id');
$('.openembed').click(function () {
generateCode();
var answerid = $(this).attr('id');
$('#box').show();
return false;
});
Use $(this). $('.openembed') refers to multiple links.
var answerid = $('.openembed').attr('id');
needs to be
var answerid = $(this).prop('id');
The other answers are trying to fix the click() function, but your issue is actually with the generateCode function.
You need to pass the clicked element to the generateCode function:
$('.openembed').click(function () {
generateCode(this);
And modify generateCode:
function generateCode(element) {
var answerid = element.id;
Of course var answerid = $('.openembed').attr('id'); within the click code isn't correct either, but it doesn't seem to do anything anyway.
Get the id when the correct anchor is clicked and pass it into your generateCode function
$('.openembed').click(function () {
var answerid = $(this).attr('id');
generateCode(answerid)
$('#box').show();
return false;
});
Change your function
function generateCode(answerid) {
// dont need this line anymore
// var answerid = $('.openembed').attr('id');

jQuery function that will remove specific word on click

I have the following information in a div
<div class="list">Abc, Test, Ready</div>
Below the div, I have this additional information
Remove Abc
Remove Test
Remove Ready
I am trying to write a jQuery function that will remove either Abc, Test, Ready (and the comma if necessary) when you click on the relevant remove link.
$('a').click(function() {
var str = $(this).attr("class");
$('.list').text($('.list').text().replace(str,''));
});
http://jsfiddle.net/PUure/
But if you really need commas removed, you need to be a bit more creative:
$('a').click(function() {
var str = $(this).attr("class");
var rgx = new RegExp(str + ',?\\s*');
$('.list').text($('.list').text().replace(rgx,''));
});
http://jsfiddle.net/PUure/4/
Edit: Updated for (lazily) removing trailing commas without regex ;)
Check the fiddle
$(document).ready(function(){
$('a').click(function(){
$('div.list').html($('div.list').html().replace($(this).attr('class') + ', ', '').replace($(this).attr('class'), ''));
});
});
You could do:
$('a').click(function(e){
e.preventDefault();
var word = $(this).attr('class');
var div = $('.list').text();
div = div.replace(word, '');
$('.list').text(div );
});
fiddle here http://jsfiddle.net/sysCc/
$('a').click(function(){
var str = $(this).attr('class');
var obj = $('.list');
var currentText = obj.text();
obj.text(currentText.replace(str,'');
});
or condensed:
$('a').click(function(){
$('.list').text($('.list').text().replace($(this).attr('class'),''));
});
You'd be better off keeping the data in an array, then modifying that array and refreshing your div with the new data.
var data = ["Abc", "Test", "Ready"];
refresh();
$("#Abc").click(function() { remove("Abc") });
$("#Test").click(function() { remove("Test") });
$("#Ready").click(function() { remove("Ready") });
function refresh() {
$("div").text(data.join(", "));
}
function remove(word) {
for(var i = 0; i < data.length; i++) {
console.log(i, data[i], word, data[i] == word);
if (data[i] == word)
data.splice(i, 1);
}
console.log(data);
refresh();
}
http://jsfiddle.net/Xeon06/dHp3b/

Categories