I have the following HTML to start with :
<div id="p_scents">
<p>
<label for="p_scnts">Friend n°1</label>
<input type="text" id="p_scnt" size="20" name="name_0" class="form-control" placeholder="Name of your friend" />
<input type="text" id="p_scnt address-input-0" class="form-control" name="address_0" placeholder="Their location"/>
</p>
</div>
<button id="addScnt" type="button">Add a friend</button>
I want to add some extra inputs with jQuery, which I succeed to do thanks to the following script:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').length + 1;
$('#addScnt').click(function() {
$('<p><label for="p_scnts">Friend n°' + i +'</label><input type="text" id="p_scnt" size="20" name="name_' + (i-1) +'" class="form-control" placeholder="Name of your friend" /><input type="text" id="p_scnt address-input-' + (i-1) +'" class="form-control" name="address_' + (i-1) +'" placeholder="Their location"/> <button id="remScnt" type="button">Remove friend</button>').appendTo(scntDiv);
i++;
console.log(i);
return false;
});
$('#remScnt').click(function() {
if( i > 2 ) {
$(this).parent('p').remove();
i--;
}
return false;
});
});
My first piece of code, that checks the click on the #addScnt element and appends a new element on the div, works like a charm.
However, my second piece of code, that checks the click on the #remScnt element and should remove its parent <p> element, doesn't work at all and I can't figure out why. I tried debugging with console.log() but I fail... Any clue would be so much appreciated!
Since remScnt is dynamic you need to delegate click, replace this line:
$('#remScnt').click(function() {
With this one:
$(document).on('click','.remScnt',function() {
BTW, ids has to be unique, make sure to replace id with class instead.
<button class="remScnt"
Related
I have a form with multiple inputs that user can append. I am able to get all the value from the inputs using jquery ajax. My issue is how to store the array on mysql? I have read about php serialize and unserialize but not quite sure to do it on my case. Below are the codes.
Form
<form>
<input type="text" name="name" class="name" placeholder="Name">
<input type="text" name="age" class="age" placeholder="Age">
<input type="text" name="gender" class="gender" placeholder="Gender">
</form>
<button type="submit" id="store" value="store">Submit</button>
<button type="button">Cancel</button>
jQuery
$('#add').click(function(){
$('#append > ul').append(
'<li style="list-style: none;">'
+ '<input type="text" name="name" class="name" placeholder="Name">'
+ '<input type="text" name="age" class="age" placeholder="Age">'
+ '<input type="text" name="gender" class="gender" placeholder="Gender">'
+ '</li>';
);
});
$('#remove').click(function(){
$('li:last-child').detach();
});
function store_siblings(e){
e.preventDefault();
var arr = [];
var submit = $('#store').val(),
$('input.nama').each(function(){
arr.push($(this).val());
});
$('input.age').each(function(){
arr.push($(this).val());
});
$('input.gender').each(function(){
arr.push($(this).val());
});
$.post('../upd-siblings.php',
{
submit : submit,
arr : arr
}, function(data){
$('#result').html(data)
});
}
$("#store").click(store_siblings);
After I make the serialization and echo I get:
a:6:
{
i:0;s:7:"MY WIFE";
i:1;s:6:"MY SON";
i:2;s:2:"27";
i:3;s:1:"2";
i:4;s:4:"WIFE";
i:5;s:3:"SON";
}
Below are the table siblings That I create on mysql:
siblings
- id
- name
- age
- gender
Can I use mysqli INSERT using the serialize values?
Checkout this link: Description, Quite good and easy to understand explanation of serialization in PHP, if you still get stuck somewhere, just comment and i'll try to clear it up.
I'm currently working on a project for which I have to develop a WordPress plugin allowing to manipulate tables in databases. My work is based on this plugin, which I'm improving and editing to match the requirements of my company : https://wordpress.org/plugins/create-db-tables/
My problem however doesn't concern MySQL, but html, Php and jQuery (especially jQuery, which I'm not familiar with, at all). It's about dynamically generating a form, itself depending on a dynamically generated form (yeah...).
With the following code, the plugin user is able to dynamically add rows to the table he's creating. I would like him to be able to add "sub-rows" (I know how to handle it server-side, my problem here is only the interface), like that :
http://i.imgur.com/XHwI54W.png
When the user clicks "Add subrows", a zone appears where he can fill out a form, etc. It works perfectly (at least the interface) for the first row, but after that, whenever I click another "Add subrows" button, nothing happens.
I'd appreciate very much if someone could take time to tell me where I'm doing something wrong. Thank you so much ! :)
Here is my code :
(the first jQuery script seemingly works, I'm not the one who developed it. I duplicated it and tried to adapt the second one to my "sub-row" requirement)
<form id="create-table" method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="add_table">
<fieldset class="table-fieldset">
<label id="table-name">Table Name:</label> <br />
<span style="position: relative; top: 2px;"><?php echo "Choose prefix (by default wp_ ) : " ?></span><input type="text" class="prefix-name" name="prefix_name" size="4" id="prefix-name"><br />
<span style="position: relative; top: 2px;"><?php echo "Choose table name :" ?></span><input type="text" class="table-name" name="table_name" size="30" id="table-name">
<span>(Alphanumeric only, no special characters.)</span> <br/> <br/>
<span><font color="blue"><strong>Will this table be used for user authentication ? </strong></font></span><input type="checkbox" class="is-user-auth" name="is_user_auth" id="is-user-auth"><br/>
<span><strong>/!\ Only one table at a time can be used for user authentication : if a current table is used for this purpose, it won't be anymore.</strong></span><br/><br/>
</fieldset>
<div id="rows">
<fieldset class="row-fieldset" id="row-fieldset" value="1"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id="subrows1" value="1"></div></fieldset>
</div>
<div id="add-row">
<button type="button" class="add-row button-secondary">Add Row</button>
</div>
<fieldset>
<input type="hidden" id="items" name="items" value="1" />
</fieldset>
<fieldset>
<input type="hidden" id="subrowitems" name="subrowitems" value="101" />
</fieldset>
<fieldset>
<button type="submit" class="button button-primary button-large">Create Table</button>
</fieldset>
</form>
<!-- Script to add rows -->
<script>
jQuery(function($) {
$('.add-row').click(function () {
$('#items').val(function(i, val) { return +val+1 });
var val_2=$('#items').attr('value');
var subrow_name = 'subrows'+val_2;
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id=\"'+subrow_name+'\" value=' + val_2 + '></div></fieldset>';
$('#rows').append(rowHTML);
});
$("input.name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>
<!-- Script to add subrows -->
<script>
jQuery(function($) {
$('.row-dynamic').click(function () {
$('#subrowitems').val(function(i, val) { return +val+1 });
var val_3=$('#subrowitems').attr('value');
var subrowHTML = '<fieldset class="subrow-fieldset" value=\"' +val_3+ '\"><label id="subrow-label">Subrow:</label><input type="text" class="subrow-name-input" name="name[]" placeholder="Name" size="20" style="background-color: #E3F6CE"><input type="text" class="subrow-type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20" style="background-color: #E3F6CE"><span id="subrow-null-label">Null</span><input type="checkbox" class="subrow-null-input" name="null[]" style="background-color: #E3F6CE"><input type="text" class="subrow-default-input" name="default[]" placeholder="Default Value" size="20" style="background-color: #E3F6CE"><span id="subrow-unique-label">Unique</span><input type="checkbox" class="subrow-unique-input" name="unique[]" style="background-color: #E3F6CE"></fieldset>';
var subrow_val = '#subrows'+$('#row-fieldset').attr('value');
$(subrow_val).append(subrowHTML);
});
$("input.subrow-name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>
You had some duplicated id's on your HTML sintax (e.g. #row-fieldset)
If you check your HTML code you initializes a fieldset tag with the row-fieldset id
<fieldset class="row-fieldset" id="row-fieldset" value="1">
and later you create a new one with the same id
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\
So when JQuery tries to find the proper id, only find the first one.
I added to the Add subrows button a value for locate the correct row
Also you did not provide any jQuery version so I used 2.2.0
Check this fiddle to see it running
Hope it helps
How do I simply add dynamic form elements but keep their values? on adding an input using my current method it doesn't pass any info typed into the fields (deleted existing: see fiddle at the bottom) I think the problem is how I am adding the new inputs document.getElementById("add_ac").innerHTML += str;
I have found other ways of adding dynamic form elements but they seem overly complicated does anyone know a very simple way of fixing the problem?
If you can't tell I don't code with JS or backend often, really just looking for a clean simple solution. Have looked on google and stack.
Any real help would be great!
<div id="add_ac">
<input type="text" name="c[]" placeholder="Add comment..."/><br />
</div>
<button id="add_ac_btn">+</button>
<div id="add_ai">
<input type="text" name="tai[]" placeholder="Add triggers, separated by commas"/> <input type="text" name="cai[]" placeholder="Add comment..."/><br />
</div>
<button id="add_ai_btn">+</button>
JS
document.getElementById('add_ac_btn').onclick = function add_new_ac(){
var str = '<input type="text" name="c[]" placeholder="Add comment..."/><br />';
document.getElementById("add_ac").innerHTML += str;
}
document.getElementById('add_ai_btn').onclick = function add_new_ai(){
var str = '<input type="text" name="tai[]" placeholder="Add triggers, separated by commas"/> <input type="text" name="cai[]" placeholder="Add comment..."/><br />';
document.getElementById("add_ai").innerHTML += str;
}
js fiddle: https://jsfiddle.net/fsdbpxoo/
Use insertAdjacentHTML as innerHTML += will reinsert all the DOM in the container.
insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.
Position "'beforeend'": Just inside the element, after its last child.
document.getElementById('add_ac_btn').onclick = function add_new_ac() {
var str = '<input type="text" name="c[]" placeholder="Add comment..."/><br />';
document.getElementById("add_ac").insertAdjacentHTML("beforeend", str);
}
document.getElementById('add_ai_btn').onclick = function add_new_ac() {
var str = '<input type="text" name="tai[]" placeholder="Add triggers, separated by commas"/> <input type="text" name="cai[]" placeholder="Add comment..."/><br />';
document.getElementById("add_ai").insertAdjacentHTML("beforeend", str);
}
<div id="add_ac">
<input type="text" name="c[]" placeholder="Add comment..." />
<br />
</div>
<button id="add_ac_btn">+</button>
<div id="add_ai">
<input type="text" name="tai[]" placeholder="Add triggers, separated by commas" />
<input type="text" name="cai[]" placeholder="Add comment..." />
<br />
</div>
<button id="add_ai_btn">+</button>
You need to append new elements instead of just replacing full content. Use .appendChild() function for that:
document.getElementById('add_ac_btn').onclick = function add_new_ac() {
var wrapper = document.getElementById('add_ac');
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'c[]';
newInput.placeholder = 'Add comment...';
wrapper.appendChild(newInput);
wrapper.appendChild(document.createElement('br'));
}
document.getElementById('add_ai_btn').onclick = function add_new_ac() {
var wrapper = document.getElementById('add_ai');
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'tai[]';
newInput.placeholder = 'Add triggers, separated by commas';
wrapper.appendChild(newInput);
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'cai[]';
newInput.placeholder = 'Add comment...';
wrapper.appendChild(newInput);
wrapper.appendChild(document.createElement('br'));
}
<div id="add_ac">
<input type="text" name="c[]" placeholder="Add comment..." />
<br />
</div>
<button id="add_ac_btn">+</button>
<div id="add_ai">
<input type="text" name="tai[]" placeholder="Add triggers, separated by commas" />
<input type="text" name="cai[]" placeholder="Add comment..." />
<br />
</div>
<button id="add_ai_btn">+</button>
Hi There use clone method to duplicate form element and insert in parent node. I made changes in your code...
HTML
<div id="add_ac">
<div id="duplicater">
<input type="text" name="c[]" placeholder="Add comment..."/>
</div>
</div>
<button id="add_ac_btn">+</button>
<div id="add_ai">
<div id="duplicetorSec">
<input type="text" name="tai[]" placeholder="Add triggers, separated by commas"/>
<input type="text" name="cai[]" placeholder="Add comment..."/>
</div>
</div>
<button id="add_ai_btn">+</button>
JS CODE :
<script>
var i = 0;
var k = 0;
var original = document.getElementById('duplicater');
var originalSec = document.getElementById('duplicetorSec');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneElement(clone.id);
}
function duplicateSec(){
var clone = originalSec.cloneNode(true); // "deep" clone
console.log(clone);
k = ++k;
clone.id = "duplicetorSec"+ k; // there can only be one element with an ID
originalSec.parentNode.appendChild(clone);
clearCloneElement(clone.id);
}
function clearCloneElement(id){
var divId = '#'+id;
$(divId).find("input[type^='text']").each(function() {
$(this).val('');
});
}
document.getElementById('add_ac_btn').onclick = function add_new_ac(){
duplicate();
}
document.getElementById('add_ai_btn').onclick = function add_new_ac(){
duplicateSec();
}
</script>
Please see here demo
Must include JQuery file in header of page
You should try using JQuery's append() method or go the vanilla JS's way and construct a node, then use appendChild() to add it.
I am working on a project in which I need to make an HTML page with couple of radio buttons.
First radio button is, INSERT. As soon as I click INSERT radio button, I would like to show three text box just below the INSERT radio button. First textbox is datacenter, second textbox is node and third textbox is data.
Second radio button is, UPDATE. As soon as I click UPDATE radio button, I would like to show same above three text box just below the UPDATE radio button.
Third radio button is, DELETE. As soon as I click DELETE radio button, I would like to show only one text box just below the DELETE radio button. In this one text box will be node.
Fourth radio button is, PROCESS. As soon as I click PROCESS radio button, I would like to show four text box just below the PROCESS radio button. In this first textbox will be datacenter, second textbox will be node, third textbox will be conf and fourth textbox will be data.
I am able to make first two radio button work (insert and update) but somehow I am not able to understand how do I make last two radio button work.
Below is my HTML
<form method="post" action="testOperation">
<input type="hidden" name="name" id="dynamicName">
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div>
<br/>
<input type="submit">
</form>
Below is my jquery -
$(document).ready(function(){
$(".changeAction").on("click", function(){
$('.changeable').html('')
var divId = $(this).attr("div-id");
$("#dynamicName").val(divId);
divId = "#"+divId;
var myInput = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" /> <label for="Node"> Node </label> <input type="text" name="node" size="20" /> <label for="Data"> Data </label> <input type="text" name="data" size="100"/>'
$(divId).html(myInput);
})
})
And here is my jsfiddle. It will be of great help if anyone can provide any jsfiddle example?
try this code in javascript part,
var datacenter = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" />';
var node = '<label for="Node"> Node </label> <input type="text" name="node" size="20" />';
var data = '<label for="Data"> Data </label> <input type="text" name="data" size="100"/>';
var config = '<label for="Config"> Config </label> <input type="text" name="config" size="100"/>';
$(".changeAction").on("click", function () {
var divId = $(this).attr("div-id");
$('.changeable').html('');
$("#dynamicName").val(divId);
switch (divId) {
case 'insert':
//insert stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'update':
//update stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'Delete':
//Delete stuff goes here!!
divId = "#" + divId;
var myInput = node;
$(divId).html(myInput);
break;
case 'process':
//process stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + config + data;
$(divId).html(myInput);
break;
}
});
SEE FIDDLE DEMO
Change your html code to this
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div><br/>
<input class="changeAction" type="radio" name="tt" value="Delete" div-id="delete"/> Delete
<div id="delete" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Process" div-id="process"/> Process
<div id="process" class="changeable"></div>
<br/>
<input type="submit">
</form>
How do I use JavaScript variables as a parameter in a jQuery selector?
<script type="text/javascript">
$(function(){
$("input").click(function(){
var x = $(this).attr("name");
$("input[id=x]").hide();
});
});
</script>
<input type="text" id="bx"/><input type="button" name="bx"/>
<input type="text" id="by"/><input type="button" name="by"/>
Basically what I want to do is to be able to hide the element which has an id that is equal to the name of the element that is being clicked.
var name = this.name;
$("input[name=" + name + "]").hide();
OR you can do something like this.
var id = this.id;
$('#' + id).hide();
OR you can give some effect also.
$("#" + this.id).slideUp();
If you want to remove the entire element permanently form the page.
$("#" + this.id).remove();
You can also use it in this also.
$("#" + this.id).slideUp('slow', function (){
$("#" + this.id).remove();
});
$(`input[id="${this.name}"]`).hide();
As you're using an ID, this would perform better
$(`#${this.name}`).hide();
I highly recommend being more specific with your approach to hiding elements via button clicks. I would opt for using data-attributes instead. For example
<input id="bx" type="text">
<button type="button" data-target="#bx" data-method="hide">Hide some input</button>
Then, in your JavaScript
// using event delegation so no need to wrap it in .ready()
$(document).on('click', 'button[data-target]', function() {
var $this = $(this),
target = $($this.data('target')),
method = $this.data('method') || 'hide';
target[method]();
});
Now you can completely control which element you're targeting and what happens to it via the HTML. For example, you could use data-target=".some-class" and data-method="fadeOut" to fade-out a collection of elements.
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
var x = $(this).attr("name");
$("#" + x).hide();
$("#" + $(this).attr("name")).hide();
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {
$("input[type=button]").click(function() {
var x = $(this).attr("name");
$(`input[id=${x}]`).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" name="bx" value="1" />
<input type="text" id="by" />
<input type="button" name="by" value="2" />
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {
$("input[type=button]").click(function() {
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" name="bx" value="1" />
<input type="text" id="by" />
<input type="button" name="by" value="2" />
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {
$(".js-hide-onclick").click(function() {
$($(this).data("input-sel")).toggle(); //use hide instead of toggle
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />
<input type="text" id="by" />
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />