here i have created dynamic elements after clicking its adding one row.but how to validate it without plugin.
var cnt = 1;
$("#anc_add").click(function() {
cnt++;
$("input[id=rows]").val(cnt);
$('#tbl1 tr').last().after('<tr><td><select name="'+cnt+'1" id="'+cnt+'1" class="Exp"><option value="0" >Select Expenses Type</option></select></td><td><textarea name="'+cnt+'2"></textarea></td><td><input type="text" name="'+cnt+'3" id="'+cnt+'3" onkeypress="return isNumberKey(event)"></td></tr>');
element_id=cnt+'1';/*alert(element_id);*/
$.ajax({
url: "../../modal/system_operator/get_companyexpenses_type.php",
dataType: "html",
type: 'POST',
success:function(json) {
var result = jQuery.parseJSON(json);
length=result.len;
/*alert(length);*/
for(k=1;k<=length;k++) {
$('#'+element_id+' option').last().after('<option value="'+eval("result.row"+k+".company_expenses_type_id")+'">'+eval("result.row"+k+".company_expenses_type")+'</option>');
}
$('select[name="'+element_id+'"]').rules('add', {required:true});
}
});
});
I assume by without plugin means you do not use jquery.validate or some other plugin to validate your input control values.
Then try the following snippet
$(document).on('blur','#form_id input,#form_id select', function(){
// write your validation logic here
});
The above code says that all (including dynamic) input,select controls within #form_id element will call the function on blur event.
Related
I have a page where users can upload up to 5 images to their post. For clarity for the user I have made it so that there are 5 empty boxes with separate input fields like this:
<span id="enableFileUpload_1" class="upload-image-svg-wrapper">
<input id="imageUploadID_1" type="file" accept="image/*"/>
</span>
<span id="enableFileUpload_2" class="upload-image-svg-wrapper">
<input id="imageUploadID_2" type="file" accept="image/*"/>
</span>
To handle these I have some JavaScript which looks for onchange event on the first field:
jQuery(function($) {
var imageNumber = 1;
$('body').on('change', '#imageUploadID_'+imageNumber, function() {
$this = $(this);
file_data = $(this).prop('files')[0];
form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', 'file_upload');
form_data.append('security', blog.security);
$.ajax({
url: blog.ajaxurl,
type: 'POST',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
alert("ok");
}
});
});
});
This works fine for the first image but it seems like imageNumber is always 1 so the onchange event only fires for the first image/input and does nothing for the rest.
Questions
Do I have to write 5 different $('body').on('change', '#imageUploadID_1', function() for each input field and then have them call the same function?
Is there a smarter way of doing this?
You can use jQuery to assign the same onClick handler to every span with a class of upload-image-svg-wrapper. You've already written the code within the handler to work on any image that is clicked because you've used this to get the form data.
$('span.upload-image-svg-wrapper > input').on('change', function() {
Above, instead of selecting the entire body of the document we instruct jQuery to select all spans with the class upload-image-svg-wrapper that are inputs. And then we remove the selector from the on change handler.
I'm trying to display some content from my database in a div, every time a user types a value into an input box. I'm using jquery to do this. But whenever I type something, once into the input box... the call-back function repeats, four times.
getProducts(){
$('.search-products').on('keyup', function(){
const searchProducts = new SearchProducts();
let search = $.trim($(this).val()); // get search text
if(search!==""){
// let data = {search: search};
let url = '/search-for-products/' + search;
$.ajax({
type: "GET",
url: url,
data: {},
success: function(response){
if(response.success){
searchProducts.showSearchProducts(response.products);
}
}
});
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control search-products" placeholder="What are you searching for ?" aria-label="Username" aria-describedby="basic-addon1" style="color: light grey;">
I'd like your honest opinions on what could be wrong, with my code. Cos, I'm now confused about what to do.
If you've not found why it's added twice, a simple fix is you can remove the listener before adding it again:
$('.search-products').off('keyup').on('keyup', ...)
You can also use namespace events, to not remove other keyup events:
$('.search-products').off('keyup.search').on('keyup.search', ...)
Not many people know that jQuery supports namespace events.
I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}
change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events
I'm programming a form with dynamic typeaheads fields, and i have found a problem when i want to show and select the suggestions.
I have two first fields, a input select and a input typeahead. When a option is selected, it's load a list of values in the input typeahead. The problem comes when i create(dynamically) a clone of this pair of fields and i want to get de list of values in the correct typeahead.
I get the id of the field (idTypeAhead) when i focus in the field and i use it in the typeahead.
This is the code:
//TYPEAHEAD
$('input.typeahead').focus(function(){
idTypeAhead = parseInt($(this).attr('id').replace('typeAhead_',''));
selectAttr = $('select#selectAttr_'+idTypeAhead).find('option:selected').val();
if(selectAttr=="null"){
selectAttr=0;
}
});
$("input#typeAhead_"+idTypeAhead).on("typeahead:select").typeahead({
name:'input#typeAhead_'+idTypeAhead,
displayKey: 'input#typeAhead_'+idTypeAhead,
input: 'input#typeAhead_'+idTypeAhead,
container:'input#typeAhead_'+idTypeAhead,
display: $(this),
suggestion: $(this),
minLength : 1,
sorter : this.query,
source : function(query, process){
return $.ajax({
url:'/aplicaciones/jsonValorAttr?selectAttr='+selectAttr,
dataType: 'json',
type:'POST',
success: function(data){
states = [];
map = {};
$.each(data, function (i, state) {
map[state] = state;
states.push(state);
});
process(states);
}
});
}
});
I have this code in form (i use Spring STS). Also i have two buttons "+" and "-". When i click "+", i clone this two fields and increase de id number of each element. When i click "-", i remove a pair of fields. (example: selectAttr_101 ->newclone: selectAttr_102).
<div class="controls">
<form:select path="rolHerramientaID" id="selectAttr_101" cssClass="field-required lstAtributos" cssErrorClass="select-error">
<form:option value="null" selected=""><spring:message code="altaAplicacion.form.seleccionar" />
</form:option>
<c:forEach var="selectAtributos" items="${resultAtributos}" varStatus="rowCount">
<form:option value="${selectAtributos.atributosId}">${selectAtributos.nombreAtributo}</form:option>
</c:forEach>
</form:select>
<form:errors path="rolHerramientaID" class="help-block" /></div>
</div>
<div class="control-group required">
<label for="input01" class="control-label"><spring:message code="altaAplicacion.form.valor" /></label>
<div class="controls">
<input id="typeAhead_101" class="input-medium typeahead" type="text" data-provide="typeahead" autocomplete="on">
</div>
How can i change the container of the typeahead dynamically?
I've been searching for the solution for this problem and found your post, with some small changes that worked for me.
I've stated the fixed input field in the form as typeAheadId_1 and created a function before create the typeahead object to manipulate the typeahead index.
on the insert operation, I increase the counter and destroy the typeahead object before each dynamic fields wrapping and recreate the typeahead object
(passing the counter) after the fields creation.
For edition (some dynamic fields are created direct in the form), I've created a REST service to return how many fields were wrapped and start counting from this.
It worked perfect for me.
If you didn´t solve or need some help, please let me know!
Following codes are working for me -
var typeaheadSettings = {
source: function (query, result) {
$.ajax({
url: "{{url('/work-order/get_parts_suggestion')}}",
data: 'txt=' + query,
dataType: "json",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
};
$('.typeahead').typeahead(typeaheadSettings); /* init first input */
$('.typeahead').on('added',function(){
$('.typeahead').typeahead(typeaheadSettings);
});
add this line after appending/creating dynamic element -
$('.typeahead').trigger('added');
Reference - https://www.bootply.com/61431
I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?