How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>
Related
I am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};
I have a string as below
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>"
Then I split it with &
var b = a.split('&');
Then further more I split b with = in loop and append to the form
$.each(b, function (index) {
var paramsV = b[index].split('=');
frm.append('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
But when it split with = that time it is splitting result string which have = inside the string and it is splitting that too. I would like to know how I can stop splitting the result string.
I this what you want to achieve, Use .split(/=(.+)/) to only split the first =
Also notice that when you try to enter paramsV[1] that has a " inside it, it will break the original code of Input, that's why I replaces it with .replace(/\"/g, "''")
var a = 'M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>'
var b = a.split('&');
var frm = $(".frm")
$.each(b, function(index) {
var paramsV = b[index].split(/=(.+)/);
frm.append('<input type="" name="' + paramsV[0] + '" value="' + paramsV[1].replace(/\"/g, "''") + '" /> ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frm"></div>
You have made a mistake in variable declaration. Inside double quotes you need to use single quotes. And you need to use regular expression like .split(/=(.+)?/). See the output below.
$(function(){
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var paramsV = b[index].split(/=(.+)?/);
console.log('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var index1 = b[index].indexOf("=")
var markup ='<input type="hidden" name="' + b[index].substring(0, index1) + '" value="' + b[index].substring(index1) + '" /> ';
console.log(markup);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Check it
I'm attempting to use .on() to add a text field when a dynamically created button is clicked. However, for whatever reason, I can't seem to get it working. Anyone see what's wrong? Thanks for any help and sorry if it's something obvious (I'm afraid that it might be but I just can't see it).
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Changes I made
► Declared variable prs as a global variable
► Remove # from the New Person button's id.
Working Demo
var prs = '';
$('#the-basics input.typeahead').keyup(function() {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Remove # from the New Person button's id.
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
Declare prs outside the click event like following.
var prs;
$('#the-basics input.typeahead').keyup(function () {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
var prs = $(this).val().split(' ');
is not a global variable, and inaccessible inside $('div#example').on('click', '#addpersonbutton', function() { so duplicate it inside your second function
EDIT: to make it clear:
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var prs = $(this).val().split(' ');
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.
I have the following code :
var currentuuid = $('#UUIDTOSEND').val();
html1 = '';
$.ajax({
type: "GET",
url: "database/Emarps/websrvc/websrvc.php?task=getData&UUID=" + currentuuid + "&DataGt=stitrtmnt",
dataType: "JSON",
success: function (data) {
client_history_list = $('#clinical_history_tbody').empty();
for (i = 0; i < data.length; i++) {
html1 += '<tr>\n\
<td class = "form-group">\n\
\n\
<input type = "text" class = "form-control facility_name col-md-6 col-sm-6 col-xs-12 " readonly="" name="facility_name[]" id = "facility_name" value="' + data[i].facility_name + '" placeholder = "Facility Name">\n\
</td>\n\
<td class = "form-group">\n\
\n\
<input type = "text" class = "form-control activity_timestamp col-md-6 col-sm-6 col-xs-12 " readonly="" name="activity_timestamp[]" id = "activity_timestamp" value="' + data[i].activity_timestamp + '" placeholder = "Visit Date">\n\
</td>\n\\n\
<td class = "form-group">\n\<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id" value="' + data[i].id + '" placeholder = "Visit ID">\n\
\n\
<button id="view_more' + data[i].id + '" class="form-control view_more' + data[i].id + '" >Select/View More</button>\n\
</td>\n\
</tr>';
$("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () {
var clinic_visit_ids = $("#" + this.id.replace("view_more", "clinical_visit_id")).val();
alert(clinic_visit_ids);
});
}
$('#clinical_history_tbody').empty();
$('#clinical_history_tbody').append(html1);
}
});
Which generates an auto table with data from the database.
I want to get the value of id from the button when I click the Select/View More button, which runs the following the $("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () { function on the script. How can I get the value of the button id and replace it so that I can use it in the clinic visit ? (When I alert I get an undefined).
The input for "clinical_visit" is never assigned a numeric value at the end of its id.
<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id" value="' + data[i].id + '" placeholder = "Visit ID">
it is instead concatenated to its class.
this goes wrong when you are tring to fetch the "clinical visit" field, since you are looking for an id with value "clinical_visit_id[number]".
It isn't there, so you end up with an empty value :
var clinic_visit_ids = $("#" + this.id.replace("view_more", "clinical_visit_id")).val();
try this :
<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id'+data[i].id+'" value="' + data[i].id + '" placeholder = "Visit ID">
OR
look for the "clinical_visit" input by class instead of id (keep in mind you still need to sanitize your HTML, since two elements should never have the same id
That would look like this :
$("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () {
var clinic_visit_ids = $("." + this.id.replace("view_more", "clinical_visit_id")).val();
alert(clinic_visit_ids);
});
You can use this script to get the id,
$("#clinical_history_tbody").on("click", "[class^=view_more]", function () {
alert($(this).attr("id"));
});
the above script wll bind click event to all the elements whose class name starts eith view_more. Then it will alert the current clicked elements id.
This is how you change the id of the button:
$("#clinical_history_tbody").on("click", function () {
var clinic_visit_ids = $(this).attr('id', "clinical_visit_id");
});
Attach event to that button onClick
onClick=giveMeID(data[i].id)
in Html and then define in JS
function giveMeID(id){
//Do whatever you want
}
Here's Example JSBIN DEMO
<html>
<body>
<button id="exa" onclick="genExamp()">Generate Example</button>
<div id="ex"></div>
<script>
function genExamp(){
var divEx = document.getElementById("ex");
for (var i = 0; i < 20; i++) {
var childBtn='<button id="view_more'+i+'" onclick="giveMeID('+i+');">View/More'+i+'</button>';
divEx.innerHTML+=childBtn;
}
}
//On Click:Gets ID and Replace it
function giveMeID(obj){
var origID="view_more"+obj;
var btn=document.getElementById('view_more'+obj);
btn.id="view_more"+obj*10;
var new_id=btn.id;
alert("Original ID:"+origID+"\n"+"New ID:"+new_id);
}
</script>
</body>
</html>