I have a jQuery function:
$(function(){
function InitDialog(c,b){
/* some code */
}
$('a[name=dialog]').click(function(e) {
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
And also I have a link defined in html code like below:
<ul>
<li>something</li>
</ul>
My question is how can I pass the parameters (caption, bodyText) to Init() function via link?
I've heard about some method like below:
<li>something</li>
But I don't understand how can I get and parse it?
Thanks
Since you are using jquery, I would recommend that you do the following to store data on your element
Link Text
Then in your click function, you can access it as shown below
$('a#dialog').click(function(){
var me = $(this), data = me.data('params');
//console.log(data);
});
Edit - Fiddle added
Check the fiddle to see a working sample
using data-* attribute, you can:
<a name='dialog'
data-caption='this is the caption'
data-bodytext='this is the body'>klik</a>
and the javascript:
$(function() {
function InitDialog(c, b){
alert('the caption: ' + c);
alert('the body: ' + b);
}
$('a[name=dialog]').click(function(e) {
caption = $(this).data('caption'); // gets data-caption attribute value
bodyText = $(this).data('bodytext'); // gets the data-bodytext attribute value
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
tho instead of using name as the selector, i'd recommend class instead
So first, I think you want to say $('a[href="#dialog"]') to get the a tags, then in the click function, $(this).attr("name") will give you the some information, which you could store a json string...
My Text
$('a[href="#dialog"]').click(function() {
var data = JSON.parse($(this).attr("name"));
InitDialog(data.caption, data.bodyText);
});
But, I don't think that's the right way of going about what you're trying to do, would you be better to create the dialog in a div lower down the page, hide it, and only show it when you click the link? Because the term 'bodyText' implies it's going to be big...
Or just:
My Link
Related
I am facing a problem in which I need to pass either one or multiple parameter to a javascript function. For example
<a href="#" OnClick="Delete(1,'q');" > X </a>
<a href="#" OnClick="Delete(2,'u');" > X </a>
But I am trying to avoid this onclick attribute from the html end. So I have used this way
</span>Delete1
</span>Delete2
</span>Delete3
And written the jQuery function like this to capture my click function from the link
$("#actRemove").each(function() {
$(this).on("click", function () {
alert($(this).data("action"));
});
});
But alas!! I am undone. This link works only for the first anchor Delete1 none of the anchors are working. Here is my jsFiddle link. I have gone through these answers Q1, Q2, Q3, Q4, Q5, Q6. Each of those question have the solution in the first way using onclick and passed the parameter to the function.I am thinking differently. Moreover my another question is, is there any way to pass parameter to a jQuery function without writing onclick in the html attribute? I know that jQuery function is capable to receive the parameter, but how can I send it to the function from the html end?
Instead of id use class selector:-
HTML:-
</span>Delete1
</span>Delete2
</span>Delete3
jQuery:-
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
Working demo:-
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</span>Delete1
</span>Delete2
</span>Delete3
Note:-
id used as unique-selector in jQuery,while class used as a group-selector
You can use this way
</span>Delete1
</span>Delete2
</span>Delete3
$("a[id^='actRemove_']").on("click", function () {
alert($(this).data("action"));
})
You can get the value of an HTML object directly in javascript without passing it with onclick using:
var object_id = document.getElementById('object_id').value;
How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/
I am pretty new in JQuery and I have the following problem.
I have create this JQuery function that when the user select a file into an input tag having id=rendicontoAllegato it put the name of this file into an hidden div having id=nomeDocumentoRendicontazione into my page
$(document).ready(function() {
$("#rendicontoAllegato").change(function() {
alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());
var selectedFileName = $("#rendicontoAllegato").val();
$('#nomeDocumentoRendicontazione').append(selectedFileName);
});
});
It works fine but the only problem is that if I first select something asfile1.txt and then select another file as file2.txt into the div having id=nomeDocumentoRendicontazione I will have the concatenation of the 2 files name.
So I will have something like file1.txtfile2.txt and it is not good for me.
How can I replace the value of the div having id=nomeDocumentoRendicontazione instead to append a new value inside it?
You can use the .text() fn if you are dealing with with your data to be inserted as text or .html() fn if you are dealing with html to be replaced
$('#nomeDocumentoRendicontazione').text(selectedFileName);
Or
$('#nomeDocumentoRendicontazione').html(selectedFileName);
Use html() instead of append().
$(document).ready(function() {
$("#rendicontoAllegato").change(function() {
alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());
var selectedFileName = $("#rendicontoAllegato").val();
$('#nomeDocumentoRendicontazione').html(selectedFileName);
});
});
You have to use
$('#nomeDocumentoRendicontazione').html(selectedFileName);
it will replace the already present HTML of that. OR you can use
$('#nomeDocumentoRendicontazione').text(selectedFileName);
it will do the same but append your data as text.
onclick="triggersTracking($(this).attr('a'),$(this).attr('b'),$(this).attr('c'),Enum.BtnSellerView)"
I have this line at various HTML tags/buttons. I want to move this code to one place for better maintainability. The problem is with third/last attribute i am passing since its Enum, it has different values being passed from different tag elements.
How can i move it to one common place where it would get invoke. For example I could have made a class if i have had just these (this).attr since its common for every tag.
You can do like
Give all the elements a common class name
Then add a data attribute, "data-enum" to each tag with corresponding value.
Then you can write the code like this,
$(".className").click(function () {
var a = $(this).attr('a');
var b = $(this).attr('b');
var c = $(this).attr('c');
var enum = $(this).data('enum');
});
You can use jquery to get this:
$("body").on("click", "someClass", function() {
//code here
});
you don't need to write $(this).attr('a'),$(this).attr('b'),$(this).attr('c')
again and agin on every onclick just paas this object and get them all in function like :
onclick="triggersTracking(this,Enum.BtnSellerView)"
function triggersTracking(obj,enumVal){
// get these values here by obj (no repetitive code needed in every onclick )
$(obj).attr('a')
$(obj).attr('c')
$(obj).attr('b')
}
Do some thing like this
.click()
.on()
.data()
if you use attributes like data-enum , data-e....
so use $(this).data() it will return all attributes in JSON which is starting
from data-
$('.click').click(function(e) {
console.log($(this).data())
$('body').append($(this).attr('a'))
})
// if you have dynamic html tag then go for .on
$('body').on('click','.click',function(){
//callback
console.log($(this).data())
$('body').append($(this).attr('a'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="click" a="i am a attr of p" b="i am b" data-a="i am data a">i am p</p>
<h2 class="click" a="i am a attr of h2">i am h2</h2>
I have to generate some li element automatically and the way I was doing it it through a function that return text inside a loop, something like this:
function getLi(data) {
return '<li>' + data + '</li>';
}
then I found a better way to do it by writing html inside a div:
<div style="display:none;" id="Template">
<li id="value"></li>
</div>
and then I would change the id and value get the html and reset the element to original state:
var element = $("#value");
element.html(data);
element.attr('id', getNewId());
var htmlText = $("#Template").html();
element.html('');
element.attr('id', 'value');
return htmlText;
then I was reading on script template
and I figured this could be a better way of doing it,
However apply the previous code didn't work as the inner elements didn't exist according to this article
so how can I apply this?
EDIT:
I put inside a ul tag, I use this method to get the items dynamically
EDIT2:
<li>
<a href="#" >
<span>
<span>
some text
</span>
</span>
</li>
this isn't necessarily what I have but something along the way
Edit3:
my ul does not exist orgialy it's generated dynamically
I insist this is not a duplicate I want to know how to use a template with some dynamic variables
You could do the following way. It's clean, reusable and readable.
//A function that would return an item object
function buildItem(content, id) {
return $("<li/>", {
id: id,
html: content
});
}
In your loop, you could do the following. Do not append each LI inside the loop as DOM manipulation is costly. Hence, generate each item and stack up an object like below.
var $items = $();
// loop begin
var contents = ['<span><span>', data, '</span></span>'].join('');
var $item = buildItem(contents, getNewId());
$items.add($item);
// loop end
Just outside the loop. append those generated LIs to the desired UL, like below.
$("ul").append($items);
This is what I'd do and I am sure there are many better ways. Hope that helps.
One option is to upgrade to a modern JavaScript framework like AngularJS and then you could do it in one line using ng-repeat.
This would serve your purpose and make you more money as a developer.
If you're going to repeat this, use a templating system. Like {{ mustache }} or Handlebars.js.
If not, you can do this.
<ul>
<li class="hidden"></li>
</ul>
And in Javascript
$('ul .hidden').clone().removeClass('hidden').appendTo('ul');
And CSS, of course
.hidden { display:none }
Try this...
function getLi(data,ID) {
return $('<li id = "'+ ID + '">' + data + '</li>');
}
It returns javascript objest of Li..and you append it where ever you need.
what you need is using jquery templates, in the bellow link you can use good one which I'm using.
you create your template and prepare you JASON object of data.
after that every thing will be ready in one function call, more details in this link.
jquery.tmpl
hope this helps you and any one come to here in future..