How to call the Method in Jquery's Append Method ?
I have the HTML code in which I use the append method() on click of a button.
I want to append the HTML with viewbag data using loop.
here is my code , is that right ?
<html>
<body>
<div class="row-fluid" id="MyCode">
</div>
<button name="AddCode"></button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function ()
{
$('#AddCode').click(function () {
$('#MyCode').append("<di ><div class='span2'>" +
//I want to call the function here...
AddDivs()
);
});
function AddDivs()
{
var ht="";
#foreach (var item in ViewBag.LocationList)
{
ht += "<div id='"+item.Id+"_"+item.Name+"'></div>";
}
}
});
</script>
Its showing undefined.
Change foreach loop with following:
#foreach (var item in ViewBag.LocationList)
{
// these lines are client codes that is in server codes
<text>ht += "<div id='" + #item.Id + "_" + #item.Name + "'></div>";</text>
}
if you dont write your js codes in <text>, razor assume that ht is an server variable.
script tag must be inside of body tag
<script type="text/javascript">
...
</script>
</body>
</html>
Related
I am working on jquery with php,Right now i have button inside loop and i want to pass "data attribute" and want to get value,Right now i am getting "undefined",So how can i do this ?
Here is my current code
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap();'><img src='assets/viewmap.png'></a>"."</td>";
<script>
function viewmap()
{
var ids = $(this).attr('data-id');
alert('id is ' + ids);
}
</script>
change your onclick to this
onclick='viewmap(this)'
and get data with jquery like this
function viewmap(elm){
var id = $(elm).data('id');
alert('id is ' + id);
}
Pass this in onclick function and get in viewmap function and access
You can try below code ..
PHP
<?php
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'><img src='assets/viewmap.png'></a>"."</td>";
?>
Script
<script>
function viewmap(m)
{
var ids = m.attr('data-id');
alert('id is ' + ids);
}
</script>
The problem is that you are using this inside your function viewmap but you are not sending it as a parameter from the HTML code, Change your onclick by: onclick='viewmap(this); than change the js function like bellow:
function viewmap(e)
{
var ids = $(e).attr('data-id');
alert('id is ' + ids);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='1254' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'>
click here
</a>
Remove onclick attribute and change the viemap() function like this
$(".map-pop").click(function(e) {
e.preventDefault();
let ids = $(this).data('id');
alert(`id is ${ids}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal'><img src='assets/viewmap.png'></a>
`
I need to display user input inside the div. But if the user put in tag, it will execute whatever inside the script tag.
For example
<html>
<body>
<button onclick="runTest('<script>alert(\'test\')</script>')">Click Me</button>
<div id="test"></div>
</body>
</html>
And my javascript runTest function
function runTest(str) {
$('#test').append($('<div>' + str + '</div>'));
}
If I run this, it will cause alert() to be executed. I tried to use escape(str), but it displays the escape characters %3Cscript%3Ealert%28%27test%27%29%3C/script%3E
Any idea? Here is the fiddler: https://jsfiddle.net/zvLg1w6q/1/
Thanks...
you can use this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
and use it same as follow:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')
<div id="myDiv">
</div>
When the batman image is clicked on it shows the 'overlay' div however that div is not clickable for some reason thus not allowing the onclick portion of the code to run. Deleting the 'document.body..... ' line of code solves this issue but why?
JS:
window.onload = function()
{
$("#overlay").hide();
}
$(document).ready(function(){
//page is ready
$("#overlay").on("click",function(){
alert("hi");
$("#overlay").fadeOut(500);
});
$('#batman').on("click",function(){
lightboxImg()
});
});
function lightboxImg()
{
var source = $('#batman').attr('src');
var text = "<img src= \"" + source + "\" id=\"lightbox-img\"/>";
document.body.innerHTML = text + document.body.innerHTML;
$("#overlay").fadeIn(0);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title> Lightbox </title>
<link rel="stylesheet" type="text/css" href="lightboxcss.css">
</head>
<body>
<div id = "overlay"></div>
<img src="batman.jpg" alt="" href="javascript:void(0)" id="batman" >
<br><br><br><br>
<p> RANDOM TEXT STUFF </p><br><br>
<p> 328ueekfuuirgh40t43h8hohro8ht </p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="lightboxjs.js"> </script>
</body>
</html>
Your handlers apply to some elements which are recreated when you append to innerHTML. You need to .prepend to body and have something like this:
window.onload = function()
{
$("#overlay").hide();
}
$(document).ready(function(){
//page is ready
$("body").on("click", "#overlay",function(){
alert("hi");
$("#overlay").fadeOut(500);
});
$('body').on("click", "#batman",function(){
lightboxImg()
});
});
function lightboxImg()
{
var source = $('#batman').attr('src');
var text = "<img src= \"" + source + "\" id=\"lightbox-img\"/>";
$("body").prepend(text);
$("#overlay").fadeIn(0);
}
document.body.innerHTML = ... overrides the element inside the body with new elements. The new elements won't have any event listeners. So clicking them won't fire any functions. So instead of ovveriding the body content with new elements use insertBefore like:
function lightboxImg()
{
var source = $('#batman').attr('src');
var text = "<img src= \"" + source + "\" id=\"lightbox-img\"/>";
//insertBefore
$(text).insertBefore($("#overlay"));
$("#overlay").fadeIn(0);
}
Use extended jQuery format like:
$(document).on('click', $(#....), function(){});
Check jQuery API for extended .on() parameters.
I have a problem(or problems) with my code, when I'm trying running the script in the developer kit trows the error
unexpected token u in JSON at position 0...
funciones.js
$(document).ready(function (){
$("#btn1").click(function(){
$.ajaxSetup({ cache: false });
var url = "productos.json";
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
for (var team in data) {
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + data[team].producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' +data[team].producto.precio + '<br/>';//precio
html += '<b>Marca: </b>' +data[team].producto.marca + '<br/>';
html += '<b>Presentación: </b>' + data[team].producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + data[team].producto.contenido + '<br/></div>';
$("#div1").append(html);
}
}));
});
});
function block(){
document.getElementById("btn1").disabled = true;
}
productos.json
[
{
"nombre":"Coca-Cola",
"precio":30,
"marca": "Cocacola",
"presentacion":"Familiar grande",
"contenido":"3Lt."
},
{
"nombre":"Coca-Cola",
"precio":25,
"marca": "Cocacola",
"presentacion":"Familiar",
"contenido":"2.5Lt."
},
{
"nombre":"Coca-Cola",
"precio":15,
"marca": "Cocacola",
"presentacion":"individual",
"contenido":"1Lt."
}
]
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="funciones.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript" src="productos.json"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="stilo.css">
</head>
<body>
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1" onclick="block()" type="button">Team location</button>
</div>
</body>
</html>
What is the problem here?Thanks in advance
There are several problems in your code. I have modified your code into a plunkr here You should visit the working plnkr to find what was corrected however I will put some snippets here also.
The line below does not do anything.
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
The actual ajax call was missing so I added it
$.ajax({
url: url
}).done(function(myData){
//your code here
}
Then the loop
html = 'Nombre: ' + data[team].producto.nombre + '[\n]';
Here data is an array so it needs to be treated as an array. Further each array item itself is producto.
So this is corrected to
for (var i = 0; i < data.length ; i++) {
var producto = data[i];
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' + producto.precio + '<br/>'; //precio
html += '<b>Marca: </b>' + producto.marca + '<br/>';
html += '<b>Presentación: </b>' + producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + producto.contenido + '<br/></div>';
$("#div1").append(html);
}
There are several issues:
url.responseText is undefined, and so the error complains on the first character of that, i.e. the u of undefined. Look at how you defined url and notice how that does no have responseText.
There is no Ajax call in your code. Use $.getJSON for this.
Do not use JSON.parse nor JSON.stringify: they only make things worse. jQuery will have done the conversion for you already.
If html is supposed to be a string, then don't initialise it as an array with [].
the onclick attribute references a function block that is not in the global scope.
Either add a click handler via code, or via the onclick attribute, but not both. So combine the code in one single click handler via one method.
The property producto does not exist in your JSON, so all the references to it will fail. Remove that property from your code, unless your JSON is different from what you have in the question
Other remarks:
You mix jQuery and non-jQuery syntax. When you have jQuery, use it. So not document.getElementById().
[\n] is a strange thing to output. I would remove that.
The loop for (var team in data) can be written with of instead of in, that way team will be the object, not the index, which makes the rest of your code simpler.
A button element doesn't need a type="button" attribute
Here is code that corrects all these issues:
HTML:
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1">Team location</button>
</div>
JavaScript:
$(document).ready(function (){
$("#btn1").click(function(){
$(this).disabled = true;
$.ajaxSetup({ cache: false });
$.getJSON("productos.json").done(function(data) {
for (var team of data) {
$("#div1").append(
$('<div>').addClass('item').append([
$('<b>').text('Nombre'), team.nombre, $('<br>'),
$('<b>').text('Precio: $'), team.precio, $('<br>'),
$('<b>').text('Marca: '), team.marca, $('<br>'),
$('<b>').text('Presentación: '), team.presentacion, $('<br>'),
$('<b>').text('Contenido: '), team.contenido, $('<br/>')
])
);
}
});
});
});
I have the code:
<script type="text/javascript" charset="utf-8">
var hash = "fifa";
$(document).ready(function() {
console.log("I am ready");
$('#trigger_but').click(function() {
console.log("Click Performed");
$.getJSON("http://search.twitter.com/search.json?rpp=100&callback=?&q=%23" + $('#hash_tag_input').val(), function(data) {
for (var i = 0; i < data.results.length; i++) {
$('#result').prepend('<div class="tweet"><img src="' + data.results[i].profile_image_url
+ '" width="50" height="60"/><span id="tweetText">' + data.results[i].text + '</span></div>');
}
});
});
});
</script>
</head>
<body>
<input type="text" id="hash_tag_input" size="40"/>
<input type="button" id="trigger_but" value="Fetch Tweets"/>
<div id="result"></div>
</body>
How would I make it so that I can use the variable hash, instead of the inputted contents of hash_tag_input as the search term. And make it so that it fetches the tweets automatically without the click of a button.
For part 1, replace $('#hash_tag_input').val() with hash.
For part 2, just put the getJSON call directly in $(document).ready, like this:
var hash = "fifa";
$(document).ready(function(){
$.getJSON("http://search.twitter.com/search.json?rpp=100&callback=?&q=%23"+hash,function(data){
for(var i=0;i<data.results.length;i++){
$('#result').prepend('<div class="tweet"><img src="'+data.results[i].profile_image_url + '" width="50" height="60"/><span id="tweetText">'+data.results[i].text+'</span></div>');
}
});
});