Should I change "click" to "bind" ?, it does not work together - javascript

Good morning, I have these two javascript codes but I can not get both of them working. When both are embedded in my page the code that is responsible for uploading documents to a folder stops working. I do not see the error anywhere, where am I failing? Thanks in advance.
$(function() {
// grab the file input and bind a change event onto it
$('#file').bind("change", function() {
// new html5 formdata object.
$('#botondecarga').hide();
$('#cargando').show();
var formData = new FormData();
formData.append('carpeta', $('#carpeta[name="carpeta"]').val());
//for each entry, add to formdata to later access via $_FILES["file" + i]
for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
formData.append("file" + i, document.getElementById('file').files[i]);
}
//send formdata to server-side
$.ajax({
url: "file-upload.php", // our php file
type: 'post',
data: formData,
dataType: 'html', // we return html from our php file
async: true,
processData: false, // tell jQuery not to process the data
contentType: false,
// tell jQuery not to set contentType
success : function(data) {
confirm("Documentos subidos satisfactoriamente.");
location.reload();
},
error : function(request) {
console.log(request.responseText);
}
});
});
});
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div id="cantidadstock" class="cantidadstock"></div><div class="form-group"><label>Producto</label><select class="form-control select2" name="producto[]" id="producto" required><?php
$clase_newstock->lista_productos_almacen_principal_formulario();
?></select><label>Cantidad</label><input type="number" name="cantidad[]" class="form-control" value=""/><div class="form-group"><label>Fecha recepcion</label><div class="input-group"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" id="fecha_recepcion" name="fecha_recepcion[]" class="form-control"></div><div class="form-group"><label for="nombre">N albaran proveedor</label><input type="text" class="form-control" id="albaran_proveedor" name="albaran_proveedor[]" placeholder="El numero de albaran del proveedor..."></div><div class="form-group"><label for="precio">Precio</label><input type="number" class="form-control" id="precio" name="precio[]" placeholder="Precio...(Solo números y punto para decimales) "></div><br>Quitar producto</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
$('.select2').select2();
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});

Related

How to perform textbox search with matching dropdown options using only JavaScript/Ajax

I am working on a Web development project. I need to take some input like bank name in a textbox. After user starts typing 3 letters, I need to show all the matching options below (Not clear how to show). In the below options user can click any one options and the clicked text should be pasted in the same text box. All should be in html, css, js or ajax.
So far I created a text box and an ul list with no li in it and this ordered list is hidden by default. I created onkeyup event for the textbox. As the user starts typing bank names, if the text length is >=3 (Since banks keyword is minimum 3), I am filling that ul with the matching data using ajax and unhide it.
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for a Bank" title="Type in a name">
<ul id="myUL" hidden onclick="selectBank()">
And the script is:
<script>
function myFunction(){
var inp = document.getElementById('myInput');
var len = inp.value.length;
if(len>=3){
LoadBanks();
$("#myUL").show();
}else{
$('#myUL').empty();
$("#myUL").hide();
}
}
function LoadBanks(){
// for now the key is static. i will be updating it with the user input
var payload = {"key":"SBI"}
$.ajax({
url:"url",
type: "POST",
data: JSON.stringify(payload),
dataType: 'json',
success: function (data){
jsonObj = data.bankList;
var list = document.getElementById("myUL");
for (var i = 0; i < jsonObj.length; i++) {
var bank = jsonObj[i].banka;
var bankl = jsonObj[i].bankl;
var t = document.createElement('li');
t.innerHTML= bank+"-"+bankl;
list.appendChild(t);
}
},
error: function(data){
console.log(data);
}
});
}
The data is loaded sucessfully. But I don't know how to take text of which item is selected from that li's in onclick event.
You can write click event on li then inside that use $(this).text() this will give you text from li which is clicked then add that in your input-box.
Demo Code :
//just demo datas ..
var data = {
"bankList": [{
"banka": "cdc",
"bankl": "cdcde"
}, {
"banka": "cdc1",
"bankl": "cdcde1"
}, {
"banka": "cdc2",
"bankl": "cdcde2"
}]
}
function myFunction() {
var inp = document.getElementById('myInput');
var len = inp.value.length;
if (len >= 3) {
LoadBanks();
$("#myUL").show();
} else {
$('#myUL').empty();
$("#myUL").hide();
}
}
function LoadBanks() {
/*$.ajax({
url: "url",
type: "POST",
data: JSON.stringify(payload),
dataType: 'json',
success: function(data) {*/
jsonObj = data.bankList;
var list = document.getElementById("myUL");
document.getElementById("myUL").innerHTML = ""
for (var i = 0; i < jsonObj.length; i++) {
var bank = jsonObj[i].banka;
var bankl = jsonObj[i].bankl;
var t = document.createElement('li');
t.innerHTML = bank + "-" + bankl;
list.appendChild(t);
}
/*},
error: function(data) {
console.log(data);
}
});*/
}
//on click of li..
$("#myUL").on("click", "li", function() {
//get text add inside inputs
$("#selected").val($(this).text().split("-")[0])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for a Bank" title="Type in a name">
<ul id="myUL" hidden></ul>
<input type="text" id="selected">

autocomplete doesn't working on dynamic created input fields jQuery

i am facing issue in autocomplete on dynamically created fields.
as in attached picture i created dynamic fields by clicking on plus sign, and on first row autocomplete is working but on the rest that are generated dynamically autocomplete is not working.
code is for autocomplete is
$(".account_code").dropdown({
onChange: function (val) {
var id=val;
var dataString = 'id='+ id +'&type=account_code';
alert(dataString);
$.ajax
({
type: "POST",
url: "include/ajax_data.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(data)
{
console.log(data);
$("#account_description").val(data.value);
}
});
}
});
dynamic row insertion code is
function add_row()
{
$rowno=$("#bank_payment_voucher tr").length;
$rowno=$rowno+1;
$("#bank_payment_voucher tr:last").after('<tr id="row'+$rowno+'"><td><div class="field"><select class="ui search dropdown account_code" id="account_code'+$rowno+'" name="account_code[]"><option value="">Select Code</option><?php foreach (get_lookups($data_code) as $key => $value){ ?><option value="<?php echo $value['code']; ?>"><?php echo $value['code']." | ".$value['description']; ?></option><?php } ?></select></div></td><td><div class="field"><input type="text" name="account_description[]" id="account_description'+$rowno+'" placeholder="Account Description" autocomplete="" value="" required=""></div></td><td><div class="required field"><input type="text" name="remarks[]" id="remarks'+$rowno+'" placeholder="Remarks" autocomplete="off" value="" required=""></div></td><td><div class="required field"><input type="text" name="cheque_number[]" id="cheque_number'+$rowno+'" placeholder="Cheque Number" autocomplete="off" value="" required=""></div></td><td><div class="field"><div class="ui fluid action input"><input type="number" name="amount[]" id="amount'+$rowno+'" placeholder="Amount" autocomplete="off" value=""><div class="ui green icon button"><i class="pk flag"></i> PKR</div></div></div></td><td><div class="field"><div class="ui fluid action input"><i class="minus circle icon red" onclick=delete_row("row'+$rowno+'") style="font-size: 2.5em; cursor: pointer;"></i></div></div></td></tr>');
}
console is also not showing any error.
requirements are: on every dynamic row, there is a fixed drop down and on the basis of that values selected from drop down, rest of the form fields filled automatically
please help me out in this
When you run this:
$(".account_code").dropdown({
...
});
You're finding all the elements with class account_code in the DOM and assigning a behavior to them, an event, that will be triggered when the dropdown functionality is used.
That code probably runs first.
So, when you add MORE elements with that same class, they never got the assignment of that behavior.
So what you need to do, in the add_row function, is not only creating the element and appending it, but also attaching the event you want to run on dropdown.
You could use this method to reassign the behavior: https://api.jquery.com/on/#on-events-selector-data-handler
Or you could also encapsulate the first snippet (assigning behavior) in a function, so you can trigger it again every time a new dynamic element is added.
Hope this helps.
See if this helpful.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>');
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
});
//add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
$("input[name^='mytext']").autocomplete({
source: availableAttributes
});
});
// autocomplete enablement
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
i just achieved it by following code
$(document).ready(function(){
$(document).on('keydown', '.account_code', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "include/ajax_data.php",
type: 'POST',
dataType: "json",
cache: false,
data: {search: request.term,request:1},
success: function( data ) {
//console.log(data);
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.code); // display the selected text
var bank_code_id = ui.item.id; // selected value
//console.log(bank_code_id);
// AJAX
$.ajax({
url: 'include/ajax_data.php',
type: 'post',
cache: false,
data: {bank_code_id:bank_code_id,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var description = response[0]['description'];
// Set value to textboxes
document.getElementById('lookupcodeid_'+index).value = id;
document.getElementById('accountdescription_'+index).value = description;
}
}
});
return false;
}
});
});
});

How to send POST requests from dynamic fields?

I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how.
This is the form: https://i.imgur.com/6xtmt3a.png
<script>
// input field
$(document).ready(function() {
var wrapper = $(".div1");
var newbutton = $(".add_form_field");
var fields = 1;
$(newbutton).click(function(e) {
e.preventDefault();
$(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box
//$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box
//$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> Delete add </div> '); //add input box
var d = $(this).parent('form').serialize();
console.log(d);
});
//delete buttons
$(wrapper).on("click", "#delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
fields--;
})
// remove div
$(wrapper).on("click", '#s1', function(e) {
//$(this).parent('div').parent('div').remove();
var q= $(this).parent().serialize();
console.log(q);
})
//add answer
$(wrapper).on("click", "#add", function(e) {
e.preventDefault();
$(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' );
var d = $(this).parent('form').serialize();
console.log(d);
//$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' );
fields--;
})
});
$( "#quizForm" ).submit(function( event ) {
var $form = $( this ),
path = $form.attr( "action" );
payload = {"testKey":"test"};
var posting = $.ajax({
url: path,
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "application-json",
});
console.log(payload);
posting.done(function() {
console.log("posted");
});
});
</script>
I need to have a JSON file output on submit that contains the questions and answers to each question (right or wrong for now) Thanks!
I would suggest adding an attribute contains the object's key on each question - let's say it will be the "question ID".
we will have something like that:
<div class="question-container" question-id="01"></div>
Assuming that answers are an .answer div with an input inside we will have something like that on form submit:
let formObject = new Object();
$('.question-container')
.each(function () {
const questionID = this.attr('question-id');
const answersArray = new Array();
this.find('.answer input')
.each(function () { // assuming answer is a div contains an input tag
answersArray.push(this.value());
})
formObject[questionID] = answersArray;
})
/// here formObject contains the formatted form as json

Create dynamic text boxes then write to text file

So there must be an easier way to create this. I have a form with the following HTML:
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then added some JS to create new text boxes if a user needs to add more names:
Taken from: http://www.sanwebcorner.com/2017/02/dynamically-generate-form-fields-using.html
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
function check() {
var temp = document.getElementsByClassName("formElem");
if (document.getElementById("ckbox").checked) {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = false;
}
} else {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = true;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then need to write those appended values to a .CSV file using PHP and here is where I am having the issue:
<?php
// Receive form Post data and Saving it in variables
header('Location: thanks.html');
$Name = "";
$Name = #$_POST ['Name'];
// Write the name of text file where data will be store
$filename = "file.csv";
// Merge all the variables with text in a single variable.
$f_data= '
Names for people: '.$Name.' ';
$file = fopen($filename, "r+");
fwrite($file,$f_data);
fclose($file);
?>
What happens is that the last appended text box gets written into the csv file.Is there a way to pass these created text boxes so they can write to a the file? Really similar question: Pass dynamic text input to PHP in order to write to text file
But I'm not sure if this can be done with text boxes.
The problem is that every input you add has the name “name”, so PHP can only access the last one (which overwrote the others). To get around this, you can add an index to the input name or make an array of them. This can be achieved like so:
<input type="text" name="name[]"...>
So now, on the PHP script you can iterate over that array to get all the inputs, or implode all the elements into a variable:
<?php
$names = implode(", ", $_POST["name"]); // all the names, comma-separated
?>
Now you can use $names inside $f_data to see all the inputted fields.
(Thanks Fred-ii for the heads up about the quotes)

How can I extract the values entered in the input boxes generated dynamically and pass it to controller using jquery?

I have a form wherein a user can enter input boxes and remove them at a click. I want to extract the values entered in these input boxes and pass them to controller using jQuery. How do I do that?Right now I am using ids to extract the values but I do not think that is a better method because suppose I add 4 options and then I remove all of them and then again add inputs, I will not be able to track these ids and extract the values.
Here is my HTML code:
<button type="button" class="addoption" id="addoption_btn">Add more option</button>
<div id="Options">
<input type="text" name="mytext[]" id="option_1" placeholder="Option 1"/>
</div>
Here is my JavaScript:
var MaxOptions = 4; //maximum input boxes allowed
var Optionsform = $("#Options"); //Input boxes wrapper ID
var AddButton = $("#addoption_btn"); //Add button ID
var x = Optionsform.length; //initial text box count
var OptionCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxOptions) //max input box allowed
{
OptionCount++; //text box added increment
//add input box
$(Optionsform).append('<div><input type="text" name="mytext[]" id="option_'+ OptionCount +'" placeholder="Option '+ OptionCount +'"/>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
});
Here is the jQuery I am using to pass the data to my controller:
$("#addquestion_btn").click(function(){
var val= CKEDITOR.instances['question_topic'].getData();
storequestion(val);
});
function storequestion(ques)
{
$.post("/instructor/store/question",{
question: ques,
option1: $("#option_1").val(),
option2: $("#option_2").val()
},function(data){
if(data[0]==="success")
{
window.location.href = '/instructor/create/topics';
}
else
{
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}}
,'json');
}
Please use below mentioned code to read through all displayed options.
function storequestion(ques) {
obj = {};
obj[question] = ques;
$("#Options:input[name*='mytext']").each(function (index) {
obj['option' + index] = $(this).val();
});
$.post("/instructor/store/question", obj
, function (data) {
if (data[0] === "success") {
window.location.href = '/instructor/create/topics';
}
else {
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}
}
, 'json');
}

Categories