Adding a button with innerHTML property - javascript

I'm trying to add html code inside a <span id="options"></span> so I'm trying to use this:
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea('" + element.id + "')' >Add</button><br>";
}
But this is what I got,
<button type="button" onclick="updateTextArea(" textarea0')'="">Agregar</button>
My problem is with the quotes, so I later tried using createElement("button"), but now I can't add the onclick attribute.
I'm not using jQuery, so it would be nice to have a solution without it.

You need to use different quotes for the function call to updateTextArea than you do for the onclick attribute. You can't do onclick='alert('hi');', because the single quote terminates the onclick attribute.
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea(" + '"' + + element.id + '"' + ")' >Add</button><br>";
}
You should definately consider doing this at least with the proper DOM API calls. You are right to try document.createElement
To set an onclick, do something like this:
var button = document.createElement('button').
button.onclick = function(){
alert('I was clicked');
}

Can be done with escaping the quotes also:
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick=\"updateTextArea(\'" + id + "\')\" >Add</button><br>";

if you are going with second option you can use setAttribute() method.
var ele = document.createElement('button');
ele.setAttribute('onclick','method_name');

Related

Ajax serialize() doesn't include data from dynamically created divs

I have a form and I add divs here dynamically using append(). It is successful in creating the divs, and that divs have input fields inside. But the problem is, after serializing the the data from the form, it doesnt include the data from the dynamically created divs.
This is my createDiv function:
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
Is there a problem in creating my div? Why does serialize doesnt include the data from my created div?
Thanks in advance!
Here is where is serialize the data. When the form is submitted:
$('#explorer_form').submit(function(e){
var serializedData = $('#explorer_form').serialize();
alert(serializedData);
$.ajax({
url : url + api,
type : method,
data : serializedData,
success : function(response){
$('#response').val(JSON.stringify(response));
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
And the form:
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</submit>
</form>
And now, the alerted data is only the data from the input 'uname' only. It doesn't serialize the data from the created div.
Make sure your userQues is a form and that you do the serialize AFTER you added the inputs. Your code works, here: http://jsfiddle.net/9v3khbts/
HTML
<form id="userQues">
</form>
<button id="doSer">Serialize</button>
JS
$(document).ready(function(){
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
createDiv();
$('#doSer').click(function(){
alert($('#userQues').serialize())
})
});
<html>
<body>
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</button>
</form>
<div class="output"></div>
<script src="jquery.js"></script>
<script>
function createDiv () {
var count = 5;
for(var i=0; i<count; i++){
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
// "<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"<input id=data["+ i +"][questiona] name=data"+i+" type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>"
);
}
};
createDiv();
$('#explorer_form').submit(function(e){
e.preventDefault();
$(".output").text($("#explorer_form").serialize());
});
</script>
</body>
</html>
This works fine for me.
Don't use [] in ID or name.
Output will be -
You can use .appendTo() https://api.jquery.com/appendTo/ instead of .append()

Remove a Function from being repeated

Its hard to explain this so I'll try my best.
Is it possible to use .remove() to remove a javascript function from being repeated?
function
function readytouseCard() {
console.log(this);
$('.cardCVV input[name=cvv1]').keyup(function () {
console.log("s");
var checkCVV = $('.cardCVV input[name=cvv1]').filter(function () {
return $.trim(this.value).length < 3;
}).length === 0;
if (checkCVV) {
$("li.checkCode").addClass("checked");
} else {
$("li.checkCode").removeClass("checked");
}
checklistCheck();
});
function checklistCheck() {
var counting = $("li.checked:not(.title)").length;
if (counting == 6) {
console.log(counting);
$("input[name=purchase]").attr("disabled", false);
$("input[name=purchase]").removeClass("purchase-btn-disabled");
$("input[name=purchase]").addClass("purchase-btn");
} else {
$("input[name=purchase]").attr("disabled", true);
$("input[name=purchase]").removeClass("purchase-btn");
$("input[name=purchase]").addClass("purchase-btn-disabled");
}
}
}
The Main
$("li#usercurrentcc").click(function (e) {
e.preventDefault();
var selectedID = $(this).attr("data-id");
var qString = 'selectedID=' + selectedID;
$.post('/assets/inc/get-logged-info-card.php', qString, function (results) {
if ($("#usercurrentccbox, #addnewccbox").length != 0) {
$("#usercurrentccbox, #addnewccbox").fadeOut("fast", function () {
$(this).remove();
$("<div class='creditCardDetails' id='usercurrentccbox'><div class='creditCard'><div class='cardChoice'><span>Choose Card Type</span><input name='cctype1' type='radio' value='V' class='lft-field' id='visa' /><label for='visa'></label><input name='cctype1' type='radio' value='M' class='lft-field' id='mastercard' /><label for='mastercard'></label><input name='cctype1' type='radio' value='A' class='lft-field' id='amex' /><label for='amex'></label></div><!--cardChoice--><div class='cardNumber'><input name='ccn1' id='ccn' type='text' class='long-field' value='" + results[0].maskccn + "' maxlength='19' readonly /></div><div class='cardCVV'><input name='cvv1' id='cvv' type='text' maxlength='5' class='small-field' /></div><div class='creditCardName'><input name='ccname1' id='ccname' type='text' class='long-field' value='" + results[0].ccname + "' readonly/></div><div class='cardDate'><input name='exp11' id='exp1' type='text' maxlength='2' class='small-field' value='" + results[0].ccm + "' readonly /><input name='exp21' id='exp2' type='text' maxlength='4' class='small-field' value='" + results[0].ccy + "' readonly /></div></div><!--creditCard-->").insertAfter("#paymentCardChoice");
$('#usercurrentccbox .cardChoice input#' + results[0].cct + '').attr("checked", true);
$('#usercurrentccbox .cardChoice label').removeClass("active");
$('#usercurrentccbox .cardChoice label[for="' + results[0].cct + '"]').addClass("active");
$("li:not(.title,.checkCode)").addClass("checked");
});
readytouseCard();
} else {
$(".submit-btn").fadeIn();
$("<div class='creditCardDetails' id='usercurrentccbox'><div class='creditCard'><div class='cardChoice'><span>Choose Card Type</span><input name='cctype1' type='radio' value='V' class='lft-field' id='visa' /><label for='visa'></label><input name='cctype1' type='radio' value='M' class='lft-field' id='mastercard' /><label for='mastercard'></label><input name='cctype1' type='radio' value='A' class='lft-field' id='amex' /><label for='amex'></label></div><!--cardChoice--><div class='cardNumber'><input name='ccn1' id='ccn' type='text' class='long-field' value='" + results[0].maskccn + "' maxlength='19' readonly /></div><div class='cardCVV'><input name='cvv1' id='cvv' type='text' maxlength='5' class='small-field' /></div><div class='creditCardName'><input name='ccname1' id='ccname' type='text' class='long-field' value='" + results[0].ccname + "' readonly/></div><div class='cardDate'><input name='exp11' id='exp1' type='text' maxlength='2' class='small-field' value='" + results[0].ccm + "' readonly /><input name='exp21' id='exp2' type='text' maxlength='4' class='small-field' value='" + results[0].ccy + "' readonly /></div></div><!--creditCard-->").insertAfter("#paymentCardChoice");
$('#usercurrentccbox .cardChoice input#' + results[0].cct + '').attr("checked", true);
$('#usercurrentccbox .cardChoice label').removeClass("active");
$('#usercurrentccbox .cardChoice label[for="' + results[0].cct + '"]').addClass("active");
$("li:not(.title,.checkCode)").addClass("checked");
}
readytouseCard();
}, "json");
});
readytouseCard();
The function starts and works on the first click but after that it doesn't work again. console log just shows Window # and when I click again it show Window # Window #
So I was hoping there was a way to kill the function readytouseCard() using .remove();
Thanks in advance
You can't "remove" functions, you can just override them, e.g. readytouseCards = function(){}.
However I don't understand, why you want to to that. And Console logging Window is correct, because you have console.log(this); on the first line of your function. Since you call readytouseCards from global context, this is bound to window.
Your actual problem is that you attach an eventhandler inside your readytouseCards(). Thus calling the function the second time attaches the eventhandler twice. This results in checklistCheck() being called twice on every keyup. This is indicated by your console logging window twice.
You need to refactor your whole code:
Attach the eventhandler ONCE in the beginning via .on() (jQuery on()) so that elements added to the dom later on have the eventhandler attached too.
$(document).on('keyup', '.cardCVV input[name=cvv1]', function () { ... }
and kill the function readytouseCard() by moving the checklistCheck() out of it. Finally, omit the readytouseCard(); calls.
It's global, which means that we can access it through the window.
window.readytouseCard() = function(){
return false;
}
Now that we've done that, the functions contents have been replaced with return false; which will mimic nothing happening.
I have reindented your code. As you can see now, when there are #usercurrentccbox, #addnewccbox found after the Ajax request, the function will be called twice. Just remove the first one.
If you want to remove an event listener automatically after it was executed once, jQuery offers .one().
You can't delete a function. If the function is determined by an identifier each time it is invoked, you may be able to overwrite that variable with a different function. However, that won't work when the reference to the function is stored in a inaccessible variable, e.g. when added as an event listener. Then you'd need to code:
var called = false;
function executeOnlyOnce(...) {
if (called) return;
called = true;
...
}

unable to split string in jquery

<table border="0" class="commentbox">
<tr>
<td>
<div id="comment-f78d0b00-a008-473d-b647-a4a103ee3778"></div>
<input type="button" class='btnReply' id="reply-f78d0b00-a008-473d-b647-a4a103ee3778" value="Reply"/>
</td>
</tr>
</table>
$(".commentbox .btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).attr("id").split("-")[1]
alert(id);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' />
<input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
i want the f78d0b00-a008-473d-b647-a4a103ee3778 to come after split rather alert is giving
f78d0b00
I have tried to change id = comment_ f78d0b00-a008-473d-b647-a4a103ee3778 and split
id = $(this).attr("id").split("_")[1],but it doesnt work.
Edited
Input - container-f78d0b00-a008-473d-b647-a4a103ee3778
Output after split f78d0b00-a008-473d-b647-a4a103ee3778
A slightly convoluted means of achieving your end-result:
// splits the supplied string by the hyphen '-' character
var string = 'comment-f78d0b00-a008-473d-b647-a4a103ee3778'.split(/-/);
// removes the zeroeth/first element from the string array
string.shift();
// joins the remaining elements from the string back together
var newString = string.join('-');
console.log(newString);​
JS Fiddle demo.
Edited to turn the above into a function:
function splitString(haystack, needle){
if (!needle || !haystack){
return false;
}
var string = haystack.split(needle);
string.shift();
return string.join(needle);
}
// the first argument is the string you want to work on,
// the second is the character you want to split on
// f is the variable that will hold the new string
var f = splitString('comment-f78d0b00-a008-473d-b647-a4a103ee3778','-');
console.log(f);​
JS Fiddle demo.
References:
join().
shift().
split()
If the format of the string is not going to change then how bout using the substring function instead?
var str = "comment-f78d0b00-a008-473d-b647-a4a103ee3778";
var subStr = str.substring(str.indexOf("-") + 1);
alert(subStr);
This returns: f78d0b00-a008-473d-b647-a4a103ee3778
Here s a jsfiddle for the same
http://jsfiddle.net/M2Ywy/
If it works for you then your code would look like this
var id = $(this).attr("id");
var subStr = id.substring(str.indexOf("-") + 1);
alert(subStr);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' /> <input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + subStr).append(strDiv);
Demo jsFiddle
This should do it:
var id = '';
var strDiv = '';
$(".btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).prev('div').attr("id").split("comment-")[1];
alert(id);
strDiv = "<input type='text' class='txtCmnt' id='txtReply-"+ id +"' /><input type='button' class='btnSave' value='Save' id='btnSave-"+ id +"' />";
$("div[id*="+id+"]").append(strDiv);
});
You can do it this way, might be a longer version, but just 3 lines strong.
Just split() the string via the hyphens "-" and then splice the first index and then rejoin the whole string using the join() method
example: http://jsfiddle.net/eE48z/
$(document).ready(function(){
$(".commentbox .btnReply").click(function(){
var jid = $(this).attr("id").split("-");
jid.splice(0,1);
var id=jid.join("-");
alert(id);
var strDiv = "<input type='text' class='txtCmnt' id='txtReply-" + id + "' /><input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
});

How can I conduct a post via Javascript from jQuery?

I want to conduct a POST request via jQuery.
Say I have four Javascript variables: var1,var2,var3,var4 and a endpoint of URL.
How would I POST via jQuery (I would rather not be using Ajax for the sake of this example).
Put these variables into the form via hidden labels, and submit it.
If you can place a div in the html with id="myDivContent", you could add them there
var myStr = '<input name="var1" type="hidden" value="' + var1 + '" />';
myStr += '<input name="var2" type="hidden" value="' + var2 + '" />';
myStr += '<input name="var3" type="hidden" value="' + var3 + '" />';
$('#myDivContent').innerHTML = myStr;
$('form#myForm').submit();
If you just want to create a form on the fly, put these vars in there and make a POST request, then I need to update my answer.
jquery:
// var1, var2 ..., my_url must be given
$('input:hidden[name=var1]').val(var1);
$('input:hidden[name=var2]').val(var2);
...
$('#my_form').attr('action', my_url);
$('#my_form').submit();
html:
<form id="my_form">
<input type="hidden" name="var1">
<input type="hidden" name="var2">
...
</form>
No AJAX. This code actually submit your form as a normal submit action triggered by the user.
You don't need jQuery for this use-case.
I would rather create a form element(DOM) and set the variables of the form and then submit the form.
This can be done in javascript.
Here is an example.
value1 = 1234;
value2 = 5678;
value3 = 9012;
value4 = 3456;
var f = document.createElement("form")
f.method= "post"
f.action = "enpoint.url"
f.innerHTML = f.innerHTML + "<input type='text' name='var1' value='"+value1+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var2' value='"+value2+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var3' value='"+value3+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var4' value='"+value4+"'/>"
f.submit()

jquery incrementing number in html name=""

I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)

Categories

Resources