I am using jQuery for the first time. I've been searching a lot but have not gotten the answer.
I want to insert an input Type at id="star" and with value="score Star" but I'm not able to do that. Score returns the numeric value. I think the problem is in the value attribute, but I don't know where. Thanks In Advance.
Here's the code:
<script type="text/javascript">
$(function() {
$('#click').raty({
click: function(score) {
document.getElementById('star').innerHTML="<input type='text' name='type' value='"score+ "' Star >";
//alert( 'score: ' + score);
}
});
});
</script>
<label>Deal Type:</label>
<div id="click"></div><span id="star"></span></div>
You're not writing the code correctly
.innerHTML="<input type='text' name='type' value='"score+ "' Star >";
It should be
.innerHTML="<input type='text' name='type' value='"+score+" Star' >";
You're not concatenating the string, or quoting the value correctly
.innerHTML="<input type='text' name='type' value='"score+ "' Star >";
should be
.innerHTML="<input type='text' name='type' value='" + score + " Star' >";
<script type="text/javascript">
$(function() {
$('#click').raty({
click: function(score) {
document.getElementById('star').innerHTML="<input type='text' name='type' value='"+score+ " Star'>";
//alert( 'score: ' + score);
}
});
});
</script>
<label>Deal Type:</label>
<div id="click"></div><span id="star"></span></div>
A better approach is to actually create an input DOM object and append it:
$('#star').append($('<input/>').attr({
type: "text",
name: "type",
value: score + " Star"
}));
Related
I use popover of the bootstrap and then the problem. when I write javascript for append data add to the table .
The data it can not be called a popover ,
but the first Table written, it can be called popover .
This a function code add table.
function myFunction() {
var addTable = "<tr>" +
"<td><a style='cursor:pointer' data-toggle='popover' title='Vat Detail' data-html='true' " +
"data-content='Vat <input type=\"text\" id=\"txtVat[]\" name=\"txtVat[]\" size=\"8\"> </br> " +
"Invoice <input type=\"text\" id=\"txtVatInvoice[]\" name=\"txtVatInvoice[]\" size=\"8\"> </br> " +
"DATE <input type=\"text\" id=\"txtVatDate[]\" name=\"txtVatDate[]\" size=\"8\"></br> '>" +
"VAT </a> </td>" +
"</tr>";
$("#myTable tbody").append(addTable);
};
Try to trigger the popover using Javascript, look here.
This could get the job done:
$(function () {
$('[data-toggle="popover"]').popover()
});
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()
I was using select2 plugin on my input box to search items from the database using AJAX based on what the user type on it. It was working fine, I can search Items on it and select it when its available, but my problem is whenever I add new rows on my table the previous item fields "text" will be gone, I'm making a table where you can add/remove rows dynamically so here is my HTML:
<td><input name='product[0][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>
and my javascript:
function addRow(){
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
rowArrayId = rowArrayId + 1;
};
$(".itemSearch").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
here are some screenshots:
1st state:
2nd state: when searching item on the input box
3rd state: after adding new row on my table
What can be the issue?
The same id value is used for the input elements as rows get added.
It is best to have unique id within the page.
I would guess that every time you call .select2(), that all the selects get reset to the original state. You could only call the constructor on the new box by limiting the scope.
To update only the new select2s you should change the following.
See this example (untested, please adjust):
var newHtml = $("<h1>Code to be appended here</h1>");
newHtml.appendTo('#tblItemList tbody');
$('.itemSearch', newHtml).select2(/* ... */)
As an alternative you could try "freezing" the state by applying the "selected" attribute to all boxes before you call the constructor.
See this example (untested, please adjust)
$('.itemSearch').each(function(){
var val = $(this).val();
$(this).find('option[value='+val+']').attr('selected', 'selected');
})
I am trying to join two blocks of html code with javascript and call a dialog afterwards. I have done some research and tried concat and + but that doesnt work. Here is a simplified version of my code:
var html =
"<div class=\"dialog-form\" title=\"Edit\">" +
"<form class=\"insertaplato\" method=\"POST\" action=\"edit.php\">" +
"<fieldset>" +
"<label>Plate: </label> <input type=\"text\" value=\"" + plate + "\" >" +
"<label>Price: </label><input type=\"text\" value=\""+ price +"\" >";
"Spicy: <br> ";
if (spicy==1)
{var varP=
"<label> Yes </label><input value= \"yes\" type=\"radio\" checked>"+
"<label> No </label><input value=\"no\"><br><br>";
} else {
var varP=
"<label> Yes </label><input value=\"yes\" type=\"radio\">"+
"<label> No </label><input value=\"no\" checked type=\"radio\"><br><br>";
}
var html2 = "<br>"+
"<br><input id=\"insert\" type=\"submit\" value=\"Edit\" name=\"send\"> " +
"</fieldset>"+
"</form>"+
"</div>";
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
As it is right now the dialog doesnt come up. If I do this with only the first html variable it come up Ok but when I try to add or concatenate the others nothing happens. I am evidently not using these variables as I should. Any ideas?
Concatenate the strings and not the jQuery objects
var div = $(html + varP + html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
Remove the $ where you're appending the pieces together. You want to append the strings into a single object.
var div = $(html + varP + html2);
intead of
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
try this:
var div = html+varP+html2;
$('.dialog-form').dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
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;
...
}