how to append a javascript function with 2 variables in html? - javascript

I'm trying to append into the html code a javascript function with 2 variables,
the comment variable is a string and i have problem passing it :
var url = '{{URL::to('calendar/comments')}}';
$.getJSON(url+"/"+data.id, function(data)
{
ul.append("
<li>
<a href='#'onclick='openmodal("+value.id+", "+value.comment+")'>
Modifier
</a>
</li>"
);
});
but when i display in the console i get the string variable shown as a varibale
for example test and not "test" as i want and i get this error "test is not defined".

var url = '{{URL::to('calendar/comments')}}';
$.getJSON(url+"/"+data.id, function(data)
{
ul.append("
<li>
<a href='#'onclick='openmodal("+value.id+", \""+value.comment+"\")'>
Modifier
</a>
</li>"
);
});
You need to surround the comment with "" so when you trigger the click,
the onclick function as something like openmodal(1,"test") and not openmodal(1,test) since it would just try to call it with the `test variable which is undefined

Related

$(this).attr('id') gives blank values in jQuery

I have a link as follows:
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
I need to pass the value of id to another page using Framework7 as follows:
$$('.bid_accept').on('click', function (e) {
e.preventDefault();
var value = $(this).attr('id');
var jsonstring = JSON.stringify(value);
myApp.confirm('Are you sure?', 'Custom Title',
function (jsonstring) {
myApp.alert('Your name is "' + value + '". You clicked Ok button');
},
function () {
myApp.alert('You clicked Cancel button');
}
);
});
I receive alerts as:
Your name is "". You clicked Ok button
I also tried:
var value = this.id;
Why am I not getting the id value?
If you use JSON.stringfy(value) it means you are setting that ID out of a JSON value, i do not know if i am write but the ID attribute takes a 1 word name and JSON.stringfy() produces multiple words separated by spaces. Let alone i think IDs have a specific number of characters so you might be intializing a very long name.
Not really sure what you want to achieve but HTML allows you to add attributes of your own and read them in JQuery like:
<a href="#" myAttr="<?php $res['id'];?>" class='bid_accept'>Accept</a>
such that when you click your code will be like:
$$('.bid_accept').on('click', function (e) {
var value = $(this).attr('myAttr');
....
}
This line has error
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
change it to
<a href="#" id="<?php echo $res['id'];?>" class='bid_accept'>Accept</a>
And in jquery part instead of $ you have to use $$.
var value = $$(this).attr('id'); // check $$ sign

Jquery doesn't find dynamicaly dom parent

I have to develop a very large platform and I need some improvements in some plugins.
Basically, I have a template which use smarty as engine (it doesn't matter this) and I have this code in that template:
<div class="imageLoader">
<div id="main_picture" data-instance="article" data-location="{$smarty.session.CONFIG.DIR.C_PHOTOS_DIR}">
{if $data.main_picture}
<input type='hidden' name='main_picture' value="{$data.main_picture}" />
<img src="{$smarty.session.CONFIG.DIR.C_PHOTOS_DIR}{$data.main_picture}" />
<span class="NTPDelete" onclick="javascript: ntpDeleteImage(this);">
{$smarty.session.language.ntp.delete}
</span>
{else}
<span class="NTPOpenLoader" onclick='javascript: ntpOpenLoader(this);'>
{$smarty.session.language.ntp.add}
</span>
{/if}
</div>
</div>
I have also a js script which contains this code:
function ntpDeleteImage(elem) {
var parent = $(elem).parent();
var szInstanceName = $(parent).attr('data-instance');
var params = {
'filename' : encodeURI($(parent).find('input').val()),
'instance': szInstanceName
};
$.post("./ajax/ntp.delete.php", params, function(data){
})
.done(function(data){
$(parent).find('img, span').remove();
$(parent).find('input').val('');
$("<span />", {
class: 'NTPOpenLoader'
}).html(ntpAddPictureText).appendTo(parent);
$(parent).on('click', 'span.NTPOpenLoader', function(){
ntpOpenLoader(elem);
});
});
}
function ntpOpenLoader(elem){
var parent = $(elem).parent();
var szInstanceName = $(parent).attr('data-instance');
console.log(parent);
window.open("ntp.loader.php?id=" + parent[0].id + "&instance=" + szInstanceName, "_blank", "width=400,height=170,top="+event.clientY+",left="+(event.clientX-150));
}
Method ntpOpenLoader() have two contexts: first is the method ntpDeleteImage and the second is directly from template code (see template code above).
When I run ntpOpenLoader() directly from template code it works fine.
When I run ntpOpenLoader() from ntpDeleteImage() context my span dom doesn't see the parent. Actually, I don't think that my span (with NTPOpenLoader class) retrieve correctly the parent.
Debugging this from Chrome I have in console as follow:
In (template context) console return.
[div#main_picture, prevObject: n.fn.init[1], context: span.NTPOpenLoader]
In context of running from ntpDeleteImage I have:
[prevObject: n.fn.init[1], context: span.NTPOpenLoader]
This means I have an object without parent.
Please help me find my error and also correct me where I'm wrong.
I'm was totally idiot to forgot the context of elem inside of onclick event binding. The correct call is ntpOpenLoader(this). Now it's work perfectly.
Thanks folks!

How do I pass database column values as parameters of a JavaScript function?

I have a column in grid which is of hyperlink type and when I click, it should take me URL on basis of JavaScript function. Now my question is how should I pass database column name as parameter into JavaScript function. I tried something which is not fruitful.
<ItemTemplate>
<td colname="time_type" >
<a ><%#DataBinder.Eval(Container.DataItem, "TYPE_SEQ")%></a>
</td>
</ItemTemplate>
function Time_type(<%# Eval( "TIME_TYPE_INDICATOR" ) %>,<%# Eval( "TYPE_SEQ" ) %>){
var url;
if (<%# Eval( "INDICATOR" ) %> == 'O'){
url= www.something.com/<%# Eval( "TYPE_SEQ" ) %>?;
}
else if(<%# Eval( "INDICATOR" ) %> == 'T'){
url= www.something.com/<%# Eval( "TYPE_SEQ" ) %>?;
}
}
The function here is taking 2 database columns as parameters and based on one parameter other parameter is used as query string in URL. My javascript function is not working and I know it is not right way to pass paramaters like this.Please help. **Also please show me how to call this function on hyperlink click **
I might sound stupid but why use so difficult names for function(someName,someOtherName)...
For example doesn't functions work like this:
function someFunction(val1,val2){
var troll = val1+val2;
return troll;
}
var temp = someFunction(1,2); // temp is now 3. So here is the right way to call functions and pass it parameters.
I'm still quite new to coding in general but I think from hyperlink it goes like this:
<a onClick='someFunction(someValue,someOtherValue);'></a>
Also I would put in quotes when assigning variable:
url = "www.something.com/"+someVariable;

Changing function parameters onclick?

<div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe(u,$id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>
onclick how do i change the first parameter in the onclick function to 's'? So the next time it will look like this.
<div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe(s,$id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>
I wouldn't do it like you want to. See the XY Problem.
Instead, what you should so, is keep track of the subscription state of the user, either using a cookie or an identifier on the link (data-state="s"), and take notes in the function.
Instead of setting onclick in your HTML do it with Javascript soon after. I'm assuming you're echoing all your code as a double quoted PHP string because of 'us$id':
<div class='unsubscribe'>
<a id='us$id' href='#'>
<img src='/unsubscribe.jpg' alt='unsubscribe' />
</a>
</div>
<script type='text/javascript'>
document.getElementById('us$id').onclick = function(){
// Subscribe u
subscribe(u, $id);
// Set all future clicks to subscribe s
this.onclick = function(){
subscribe(s, $id);
};
};
</script>
Instead of changing the string in the onclick, you can change it in the javascript itself. This is if you want to change all of the s to u throughout the page (wasn't sure if there was only one or if this is what your intention is).
Remove the first parameter:
<div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe($id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>
Then change subscribe() to this:
function subscribe(id)
{
// doing "static" variable in javascript
if (typeof this.foo == 'undefined')
{
this.foo = 's';
}
else
{
this.foo = 'u';
}
...
}
One way would be to change it textually; use var el = document.getElementById('us$id'); to retrieve the element, then search el.attributes for an attribute with .name value "onclick", and replace its child with a new TextNode with the second function call.
A different approach would be to change the HTML so that subscribe will get both u and s, and somehow (e.g. with a global variable, a static variable, etc.) remember if it's the first or second time that this method is invoked.

Javascript to get the id of the hyperlink clicked

I would like to know how i can set the current hyperlink id to a hidden field on clicking the corresponding links. The html control code is as follows:
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="ExpressionsLink"
title="Create expression column" onclick="keepID()">Add Expressions Model</a>
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="AggregateMethodLink"
title="Create aggregate column">Add Aggregate Methods</a><input id="HiddenIdHolder"
type="hidden" />
I need the id of the link clicked on the hidden field 'HiddenIdHolder'.
Javascript
function keepID() {
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value= ? // What can i do here to get the id?
}
this refers to the element itself. Example on jsFiddle
onclick="keepID(this)"
Then
function keepID(element)
{
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value = element.getAttribute("id");
}
Use jQuery:
$('a').click(function() {
$('#HiddenIdHolder').val($(this).attr('id'))
})
You should modify your HTML to provide argument for KeepID function:
ooxx
note that you should provide a this argument when invoke KeepID function, then in KeepID function, you can access this element from argument:
function KeepID(src) {
document.getElementById("HiddenIdHolder").value = src.id;
}

Categories