I am trying to create an dynamic order form using Jquery and PHP and got stuck. I have a Jquery code that onclick adds a new set of fields. Also in that jquery code I apply some style and jquery to one of the fields. Its an Multiselect, Searchable dropdown list.
Problem here however. I can apply this style so that it has the search bar etc. to the first one. the ones after are just random multilists with no vallues or searchbar.
Here is my code:
$(document).ready(function() {
var max_fields = 100; //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
//THIS WORKS!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
//THIS DOESNT WORK!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'Remove' +
'</div>' +
'<div><input type="number" name="quantity'+ x +'" min="1" max="10">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<div class="input_fields_wrap">
<form method="post"><input type="submit" value="Add item" class="add_field_button"></form>
<div>
<select id="country1" multiple="multiple" style="width:300px;">
<!-- Dropdown List Option -->
</select>
</div>
</div>
So in the Jquery I put 2 comments in caps rage to mark what I mean that doesnt work.
Screenshots:
This on first sight
When I click in the multiselect tab this works.
Picture speaks for itself. just messed up and if I click it nothing happends.
You're initializing select2 before the HTML element exists:
$("#country" + x).select2({
data: arrayFromPHP
});
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'etc...');
The select2 line should come AFTER you create the element with the append method. Try this (note that I didn't copy the whole text: this is just illustrative):
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'etc...');
$("#country" + x).select2({
data: arrayFromPHP
});
Edit Try this:
var newContent = $('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'Remove' +
'</div>' +
'<div><input type="number" name="quantity'+ x +'" min="1" max="10">Remove</div>'
)
$(wrapper).append(newContent);
newContent.find("#country" + x).select2({
data: arrayFromPHP
});
Related
I have a table of unique tasks and underneath it a dropdown list of tasks that can be added.
I want the dropdown list and table to be dynamic because a task cant be in both dropdownlist and table.
So the dropdownlist only containts tasks that are not in the table already.
So if I select a task and click add, it moves to the table (and is no longer in the dropdown). But then if I remove the task from the table it should go back in the dropdown list. This functionality works if the row is already in the table (i.e. in the initial page load), however if I add one to the table and remove it it doesnt go to the dropdown lists.
Here is the js code that moves from dropdown to table
$('#addTaskButton').on('click',function() {
var taskId = $('select[id=processorTasksId]').val();
if (taskId == 0) {
return;
}
var task = $( "#processorTasksId option:selected" ).text();
$('#tasksTable').append('<tr><td>' + taskId + '</td>'
+ '<td>' + task + '</td>'
+ '<td contenteditable=\'true\'>0</td>'
+ '<td><input type="button" value="X"></td></tr>');
$( "#processorTasksId option:selected" ).remove();
});
and here is the JS to remove from table.
$('#tasksTable').on('click', 'input[type="button"]', function(){
var taskId = $(this).closest('tr').children('td.taskIdCol').text();
var taskDescription = $(this).closest('tr').children('td.taskDescriptionCol').text();
$(this).closest('tr').remove();
console.log("id = " + taskId);
console.log("desc = " + taskDescription);
$('#processorTasksId')
.append($("<option></option>")
.attr("value",taskId)
.text(taskDescription));
});
The console log for the problem scenario shows as follows and it just adds an empty option to the dropdown list
id =
desc =
Any idea as to how to fix it?
The problem is with the missing classes for td's added to the table as part of the script.Check below working code
$(function() {
$('#addTaskButton').on('click',function() {
var taskId = $('select[id=processorTasksId]').val();
if (taskId == 0) {
return;
}
var task = $( "#processorTasksId option:selected" ).text();
$('#tasksTable').append('<tr><td class="taskIdCol">' + taskId + '</td>'
+ '<td class="taskDescriptionCol">' + task + '</td>'
+ '<td contenteditable=\'true\'>0</td>'
+ '<td><input type="button" value="X"></td></tr>');
$( "#processorTasksId option:selected" ).remove();
});
$('#tasksTable').on('click', 'input[type="button"]', function(){
var taskId = $(this).closest('tr').children('td.taskIdCol').text();
var taskDescription = $(this).closest('tr').children('td.taskDescriptionCol').text();
$(this).closest('tr').remove();
console.log("id = " + taskId);
console.log("desc = " + taskDescription);
$('#processorTasksId')
.append($("<option></option>")
.attr("value",taskId)
.text(taskDescription));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="processorTasksId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="button" id="addTaskButton" value="Add" />
<table id="tasksTable">
</table>
I'm working with jQuery Mobile in a google web app and just having some issues selecting a tag. More specifically, I have content that is loaded from an external source so need to have a loading page initially. Once the external source is available I then update the page with the content using jQuery. Included in this content is an input tag. The issue is when I update the page, I cannot then cannot find the value of this input tag.
Here is my code below:
(intial html - Before content is loaded)
<div class="ui-body ui-body-a">
<div id="googleList" >
<fieldset data-role="controlgroup" data-mini="true" >
<input type="checkbox" name="checkbox-v-6a" id="checkbox-1-a">
<label for="checkbox-v-6a">Loading . . . </label>
</fieldset>
</div>
</div>
Here is my jQuery to update the code above when the new content comes in:
function showTaskList(tasks)
{
//Generate HTML
var htmlToInsert = "<fieldset data-role=\"controlgroup\" data-mini=\"true\" >";
for(var i = 0; i < tasks.length; i++)
{
htmlToInsert += "<input type=\"checkbox\" data-id=\"" + tasks[i][1] + "\" name=\"checkbox-" + i + "-a\" id=\"checkbox-" + i + "-a\" class=\"custom taskCheckBox\" ";
if(tasks[i][2] != undefined)
htmlToInsert += "checked=\"checked\"";
htmlToInsert += " />";
htmlToInsert += "<input id=\"currency-controlgroup1\" data-id=\"" + tasks[i][1] + "\" type=\"text\" value=\"" + tasks[i][0] + "\" data-wrapper-class=\"controlgroup-textinput ui-btn\" class=\"taskinputBox\">";
}
//Insert HTML into site
$("#googleList").html(htmlToInsert + "</fieldset>");
//Refresh List
$("#googleList").trigger("create");
}
Here is my code to get the input tag value
$(document).ready(function(){
function processTaskList()
{
console.log("Test");
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("data-id");
console.log("CheckBox:" + checkBoxId );
});
}
});
CheckBoxId keeps coming back undefined when I click on one of the checkboxes. I want to be able to read the data-id value. I'm not sure how to fix this? Any help is appreciated.
I tested the code below again, and it works - Thanks for your help
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("id");
console.log("CheckBox:" + checkBoxId );
});
I'm working on a project for school that involve converting a form into HTML. At one point there is a drop down that asks if you are applying to be a TA or a PLA. When selected, I want a new text box to appear below that drop down. Here is what I have:
This is the dropdown data in my controller:
$data['selection'] = array("TA (Graduate Student)", "PLA (Undergraduate)");
Here is what is in the view:
<label for="studentSelection">What position are you applying for?
<?php echo Form::select(array( 'name'=> 'position', 'id' => 'position', 'class' => 'form-control', 'data' => $data['selection']));?>
</label>
This is what I'm attempting:
$("#position").change(function() {
//one selection is 1, the other is 0.
if ($("#position").val() == 1){
var row = $("<div class='row' id='row_position></div>");
var year = $('<div class = "col-md-6"></div>');
var position = $('<input type = "text", id="position1", name="position1" class="form-control"></input>');
$("#position").append(row);
row.append(year);
year.append(position);
//alert works when PLA is selected.
//alert("hello");
}
else {
//something else
}
I can't quite figure it out
I tried to fix the errors in your code: https://jsfiddle.net/840xyrL7/1/
<select id='position'>
<option value="1">Item1</option>
<option value="2">Item2</option>
</select>
$("#position").change(function() {
//one selection is 1, the other is 0.
if(this.selectedIndex === 1){
var row = $("<div class='row' id='row" + this.selectedIndex + "'></div>");
var year = $('<div class = "col-md-6"></div>');
var position = $('<input placeholder="Your text" type="text" id="position' + this.selectedIndex + '" name="position' + this.selectedIndex + '" class="form-control"></input>');
year.append(position);
row.append(year);
$("#position").after(row);
}
});
Here are the lessons learned for you:
Do not put comma between the attributes: type = "text", id=
Be careful about closing quotes: id='row_position></div>
Do not use append if you want to add a new control next to another control: $("#position").append(row);, instead use .after()
<div class='row' id='row_position></div>
You're missing a closing single quote for id, which is probably breaking everything. Try replacing that with
<div class='row' id='row_position'></div>
I am trying to execute the function that was created separately called uploads.js . This javascript file is a custom image uploader function to be used in Wordpress. I was able to run that javascript file whenever i create a new button just by the of the HTML by sending the needed parameters.
There is a part where i created a dynamic button creation function using jquery, where whenever a 'PLUS' sign button is pressed, that function will trigger and a new button is added. The id of that button is automatically incremented by one.
The problem here is, whenever i click on the button that was created not by using the dynamic button function, it was able to execute the uploads.js function. But the dynamic created buttons are not able to. It seems like the id of the dynamic button was not detected. I even inspect the element of that page, the id that was sent is exactly the same from what I have sent as a parameter to the uploads.js function.
Is there something that i have missed or I have done wrong? Below are the codes:
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
uploads.js
jQuery(document).ready(function($){
function dynamic_image( button , textbox )
{
var custom_uploader;
$(button).click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
}
dynamic_image('#upload_image_button' , '#upload_image');
dynamic_image('#section2_1' , '#section2_text1');
dynamic_image('#section2_2' , '#section2_text2');
dynamic_image('#section2_3' , '#section2_text3');
dynamic_image('#section2_4' , '#section2_text4');
dynamic_image('#section2_5' , '#section2_text5');
});
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Other button(like #section2_2, #section2_3 ...) maybe not exist, When function dynamic_image run.
Then below code cannot have meaning.
dynamic_image('#section2_2' , '#section2_text2');
// cannot find #section2_2 , because not yet added
Try this.
// function is called when input.button(like #section2_1, #section2_2 ...) on #TextBoxesGroup clicked
$('#TextBoxesGroup').on('click','input.button',function(e){
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
})
See example
indicate actually like following
$('#TextBoxesGroup').on('click','input.button',function(e){
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var indicateKey = clickedInputId.substring(10,clickedInputId.length);// 2
var neededTextId = 'section2_text'+indicateKey ; //section2_text2
var $neededText = $("#" +neededTextId ); // JQuery Object of section2_text2
// run logic what you want to do
})
I am trying to detect the current button click to assign values to its respective textboxes. Each time I select any of the button, it will detect the first button click and assign the value to the first textbox. Meaning to say that, the second and third button values are assigned to the first textbox. The upload_textbox variable is not changing its value.
I did some error testing, when upload_textbox variable enters custom_uploader.on('select', function(), the value stays and will not change. I am not sure on why it doesn't.
What have I done wrong here? Below are my codes:
function dynamic_image( button )
{
var custom_uploader;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var upload_textbox = '#' + 'upload_image_' + clickedInputId;
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
//console.log(upload_textbox);
});
//Open the uploader dialog
custom_uploader.open();
})
}
dynamic_image('#TextBoxesGroup');
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
var newUploadDiv = $(document.createElement('div'))
.attr("id", 'UploadDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title_section2_' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc_section2_' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newUploadDiv.after().html('<input type="text" name="image_url_' + counter +
'" id="upload_image_section2_' + counter + '" >');
newUploadDiv.appendTo("#TextBoxesGroup");
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Then I suspect this could be the culprit.
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
This would always give you instance of first custom_uploader object.
Try to destroy the previous instance and generate new one.
There might be issue with the event binding within dynamic_image method.
Try
$(button).live('click',function(e) (deprecated as of jQuery 1.7 though)
or
$( document ).on( 'click', button, data, function(e)
instead of
$(button).on('click','input.button',function(e)
I hope it helps.
Can you try following.
$(button).change(function(){
//Write code here
});
I have solved my question. The culprit behind this was the custom_uploader mentioned by #Aman. There was a return statement there where it made the function not to take the new value that has been replaced. After doing so, the custom_uploader opens twice because there is two statement of it which it was called. Did it into an if else statement and had it the way I wanted. Below is my updated code.
function dynamic_image( button )
{
var custom_uploader;
var upload_textbox;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);
var clickedInputId = $clickedInput.attr('id');
upload_textbox = '#' + 'upload_image_' + clickedInputId;
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
});
if (custom_uploader) {
custom_uploader.open();
}else
//Open the uploader dialog
custom_uploader.open();
})
}
#Aman, you have mentioned about optimizing it. It seems quite fast at the moment. Maybe if there is a way to optimize it for the better, it would be a great help.
Thank you all, #Regent, #Aman, #Bhushan Kawadkar, #Arindam Nayak, #Raj