I have a form in which I add new file input fields as the user needs. I'm surrounding the input by a div, as so:
<div id="fileinputs">
<div class="myinput">
<label for="PropertyPic01">Photos</label>
<input type="file" name="data[Property][pic01]" id="PropertyPic01">
</div>
</div>
My jQuery code does the following:
//Add Pic link
$('#addPic').click(function(e)
{
if(!window.fotoCtr)
{
window.fotoCtr = 2;
} else
{
window.fotoCtr++;
}
if(window.fotoCtr == 5)
{
$('#addPic').html('');
}
e.preventDefault();
$('div#fileinputs').html($('div#fileinputs').html() +
'<div class="input file">' +
'<input type="file" name="data[Property][pic0' + window.fotoCtr + ']" id="PropertyPic0' + window.fotoCtr + '">' +
'</div><br/>'
);
})
The issue I'm having is that adding another file input field as I do above causes the selected files from other inputs to be removed. Is there anyway to fix this?
Use instead of html() the append() method, this will keep data bound to previous elements as files:
$('div#fileinputs').append(
'<div class="input file">' +
'<input type="file" name="data[Property][pic0' + window.fotoCtr + ']" id="PropertyPic0' + window.fotoCtr + '">' +
'</div><br/>');
Related
I have a functionality where in a table, I can click an add button and a new tr gets prepended to the table. However, I want field AddOn to get disabled if a certain food category is selected. It is easy to tackle it on change but how to do it when I click on add and depending on the value originally selected in dropdown?
var index = 0;
var FoodCategory = "FoodCategory" + index;
var tr = '<tr class="row">' +
'<td></td>' +
'<td></td>' +
'<td><select id="' + FoodCategory + '" type="text" class="form-control" /><span id="FoodCat""></select></span></td>' +
'<td><span><select id="' + AddOns + '" class="form-control"></select></span><span id="AddOns"></span></td>' +
'</tr>';
("#tblFood").prepend(tr);
I'm trying to access the value of FoodCategory to disable the select of AddOns by
$('#'+FoodCategory).val() but it is not working.
Custom placeholders can be constructed along with text areas in Javascript like this:
var custom_placeholder = "hello";
html = '<textarea class="form-control">' + custom_placeholder + '</textarea>';
However, I cannot figure out how to do this for input tags. Below does not work. The custom placeholder appears outside the input box. So how can this be done?
html += '<input type="text"/>' + custom_placeholder;
The following syntax is not allowed as well.
html += '<input type="text">' + custom_placeholder + '</input>';
Vanilla JS
var txt = 'Hello',
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', txt);
document.body.appendChild(input);
jQuery
var txt = 'Hello';
$('body').append('<input type="text">');
$('input').attr('placeholder', txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
All you need is to concatenate the placeholderattribute within your String, like this:
html += '<input type="text" placeholder="' + custom_placeholder + '"/>';
Demo:
This is a working snippet:
var html = "";
var custom_placeholder = "A Text input";
html += '<input type="text" placeholder="' + custom_placeholder + '"/>';
document.body.innerHTML = html;
Note:
You better create the elements dynamically and append their
attributes using JavaScript.
You don't need </input> for inputs in HTML, just add a / before closing your input tag.
Also make sure the custom_placeholder variable doesn't contain special characters such as " or '.
Just use html input's placeholder attribute to set placeholder text:
let html,customPlaceholder;
html += '<input type="text" placeholder="' + customPlaceholder + '" />'
Or, if what you are looking for is actually a preset value (that the user will have to delete to enter their own input), use html's value attribute:
let html,customPlaceholder;
html += '<input type="text" value="' + customPlaceholder + '" />'
I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;
I am dynamically generating the input box using jquery and then embedding it into the document. The problem I am having is, although the correct value is being shown in the inspector, the browser shows an invalid value.
To be further clear, here is the image:
You can see that, in the inspector
<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="1000" tabindex="29">
the value is 1000 while that being shown in the browser window is 1500. Can anyone please have a look and tell me, what's the problem here?
P.S: Have tried it in firefox as well. But still the problem is same i.e. different value in the inspector.
Here is the JS code:
function addrow(itemName, itemid, godown, godownid, quantity, rate, amount, gstAmount) {
gstAmount = typeof gstAmount !== 'undefined' ? gstAmount : '0';
if (typeof dTable1 != 'undefined') {
// dTable1.fnClearTable();
//$('#ItemRows').find('a[name="btnDelItem"]').off();
dTable1.fnDestroy();
// $('#ItemRows').empty();
}
//alert($('#ItemRows tr').length);
var strRow = '<tr id="row' + ($('#ItemRows tr').length + 1) + '">' +
'<td class="">' +
(($('#ItemRows tr').length + 1)) +
'</td>' +
'<td class="tdItemName" style="widtd: 250px">' +
itemName +
'<input name="hfItemId" style="width:200px;" type="hidden" value="' + itemid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
godown +
'<input name="hfGodownid" style="width:200px;" type="hidden" value="' + godownid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
'<input name="txtTblQuantity" style="width:200px;" class="num" type="text" value="' + quantity + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblRate" style="width:70px;" class="num" type="text" value="' + rate + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="' + amount + '"/>' +
'</td>' +
'<td>' +
'<input name="txtTblGstAmount" class="num" style="width:70px;" type="text" value="' + gstAmount + '"/>' +
'</td>' +
'<td class="ms"><div class="btn-group1"> <a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title=" edit " name="btnDelItem" data-id="' + ($('#ItemRows tr').length + 1) + '" ><i class="icon-remove"></i></a> </div></td>' +
'</tr>';
console.log(strRow);
console.log(amount);
$('#ItemRows').append(strRow);
//SaveNewParty($("#drpAccId option:selected").text());
bindGrid();
//dTable1.fnDraw();
PopulateTotal();
// $('#ItemRows').find('a[name="btnDelItem"]').off();
var insertedRow = $('#ItemRows tr')[$('#ItemRows tr').length - 1];
$(insertedRow).find('a[name="btnDelItem"]').on('click', function () {
var row = $(this).parents('tr');
dTable1.fnDeleteRow(dTable1.fnGetPosition(row[0]));
$('#ItemRows tr').each(function (index) {
$(this).find('td:nth(0)').text((index + 1));
});
PopulateTotal();
})
$('#datatable_Items').css('width', '100%');
Populate_Events();
}
I just had a look at your code and found that there was no problem in the code you have shown us here. I agree with Afzaal Ahmad Zeeshan but the way he has explained it, it's not always the case. I recently had the same issue and after hours of scratching my head I found out that the value was being changed by some other jquery code.
Also note that, it is not always the case that the value set by the jquery is shown in the inspector for example, if you try $("#inputel").val(4), you will note that the value will not be updated in the inspector but in the backend this value has been updated. Inspector only shows the value that was sent from the server, not the one you set by jquery or something else.
Hope you got my point!
Kamran, that's of no importance. You are setting this value NOT DYNAMICALLY. Yes, you can see here! You are either setting this value while loading the page, or you are using some other code, that you are not showing us! I am not sure of that. Ok here.
In my example you can see, I am writing a text in the input but there is no value update in the element's inspection.
Also, its maybe not the answer but you can see that you're using widtd which is not a correct CSS property. The correct one is width. You know that.
I am sure you won't get any problem while sending the form to the server, as the value will get updated by the value that you just wrote.
I have seen your code, you are writing the field as:
<input name="txtTblAmount" class="num"
style="width:70px;" type="text" value="' + amount + '"/>'
According to me, the issue is at amount. You are havin this field in the function too.
function addrow(itemName, itemid, godown,
godownid, quantity, rate, amount, gstAmount) {
Now what you can do to prevent that is to change the value of amount there. If you donot want to change it, then its OK. And also, once again you should not fear this value difference, as once you click submit the value that you have entered will be sent to the server instead of value of the field itself. The value is just because you have it written there. Nothing else, so don't worry! Its ok. You cannot change the value now, if you want to. Then here is the hell code, you will have to hard code it. Like this!
<div id="input">
<input type="text" id="text" value="" onkeyup="updateVal()" />
</div>
function updateVal() {
// start function..
var val = $('#text').val(); // the value of field..
// after getting the value, update the div..
$('#input').html("<input type='text' id='text' value='" +
val + "' onkeyup='updateVal()' />");
}
But note, after using this code, you will get the current value in the field! But you will loose the focus on the input field. As the div will get updated but the values will be the newest ones!
Now to keep in focus?
You can use this:
$('#text').focus();
But while using this, you will get only one ONLY ONE word in the field.
Why?
Because once if will focus on the field, it will (select all) select the words or value inside the field and when you press another word, it will replace the previous one with the latest one! This way you will not get any correct field I mean the field of your choice! But you issue will be fixed.
So kamran believe me, let it be the way it is! You donot want to hard-code it. If you still wanna give it a try, use the code I shared!
Example for the code I am sharing is as under:
Now when you right the value or some words, you will get the value auto updated when you see this Developer Tools. Like this:
That was all. I gave you two options for your work. And still I will love to go with the option of Not using a code, to just update the value on the field. Rest is upto you Kamran.
Edit:
You mentioed that you want to use the value 1000 not the value that the user would add to the input. Then use this:
$("name='txtTblAmount'").val() == "1000");
This will automatically override the value that user will add and replace it with the value that you want to get!
I've got a problem with another dojo enabled form that I am working on. A user can enter details onto the page by entering the data using a dialog box, which in turn updates the database and then displays the user data entered on to the form.
Each element added consist of 2 x Validation Text boxes 1 x FilteringSelect. When it's added to the page they are added as simply text boxes.
I've tried just adding as standard strings but that means the dojo.parse() does not run on the code. I've also tried programmatically adding the elements but that just displays the element object as a string to the page. So far I have:
var xhrArgs = {
url: url,
handleAs: "text",
preventCache: true,
load: function(data){
var idResult = parseInt(data);
if(idResult > 0){
var divStr = '<div id="employ_' + idResult + '" style="float:left;width:100%;">' +
'<table width="300">' +
'<tr>' +
'<td height="29"><Strong>' +
'<input type="text" dojoType="dijit.form.ValidationTextBox ' +
'change="markEmploymentForUpdate(); ' +
'id="cmpy_'+ idResult +'" '+
'required="true" ' +
'promptMessage="Please enter a valid company name" ' +
'invalidMessage="please enter a valid company name" ' +
'trim="true"' +
'value="'+ companyname +'"/>' +
'</td>' +
'<td height="29"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" onchange="markEmploymentForUpdate();" id="roleInput_'+ idResult +'" value="'+ jobrole +'" ></td>' +
'<td height="29">' +
'<input type="text" dojoType="dijit.form.ValidationTextBox" onchange="markEmploymentForUpdate();"' +
'id="jtitle_'+ idResult + '"' +
'required="true"' +
'promptMessage="Please enter your job title"' +
'invalidMessage="Please enter your job title"' +
'value="'+ jobtitle + '"/>' +
'</td>' +
'<td height="29"><img src="/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor=\'pointer\';" onclick="removeEmployer(\'employ_'+ idResult +'\', '+ idResult +')" /></td>' +
'</tr>' +
'</table>' +
'</div>';
dijit.byId('companydetails').hide();
dijit.byId('employername').setValue('');
dijit.byId('jobtitle').setValue('');
dijit.byId('jobrole').setValue('');
dojo.byId('data-table').innerHTML += divStr;
dojo.byId('companydetails').hide();
}else{
dojo.byId('add-error').innerHTML = '<div class="error">Unable to process your request. Please try again.</div>';
}
}
};
var deferred = dojo.xhrGet(xhrArgs);
This is displaying text boxes as the dojo.parse isn't running on this. If I replace the ValidationTextBox with:
var textbox = new dijit.form.ValidationTextBox({
id:"cmpy_" + idResult,
required:true,
trim:true,
"change":"markEmploymentForUpdate();",
promptMessage:"Please enter a valid company name",
value:companyname
});
I just get the object printed to the page.
Any ideas how I can added this to my page and maintain the dojo component rather than it defaulting to a text box?
Many thanks.
dojo.parser.parse(dojo.byId('data-table')); after you set it's innerHTML