I want to develop a webpage wich dynamically adds and removes particular webforms (all webforms with the same structure) on the page (when pressing add and remove buttons). Adding and removing the webforms already works in the code below (using a jquery function), but I still struggle to create the related unique name values when submitting more forms. My idea is:
- to put all forms in an array (forms() )- each with unique name values
- ...and maintain in a array (formsavailable()) which forms have been added/used and which have been removed.
I already added the code (below) to maintain formsavailable() when adding forms. But I dont know how to code formsavailable() for removing forms.
Any ideas? Or are there simpler ways for creating the unique name value's with the described context?
Please your comments.
Thank you.
The code:
<script>
var forms = Array();
var formsavailable = Array();
forms = getProductconfigforms(); //create a list of strings with the product forms
var NUMBER_OF_FORMS = 5;
for (var i=1; i<=NUMBER_OF_FORMS;i++)
{
formsavailable[i] = true; //at the start all forms are
}
//script for adding and removing productss
$(document).ready (function () {
var i;
$('.btnAdd').click (function () {
i = formsavailable.indexOf(true);
$('.buttons').append(forms[i]); // end append
formsavailable[i] = false;
$('div .btnRemove').last().click (function () {
$(this).parent().last().remove();
}); // end click
}); // end click
}); // end ready
</script>
</head>
<body>
<h2> text here </h2>
<div class="buttons">
<input type="button" class="btnAdd" value="Add"><br>
</div>
<p> tekst </p>
<input type="button" value="Terug naar stap 1" onclick="goBack()">
</body>
You actually don't need to make a unique index or unique name. The HTTP protocol supports sending multiple data points with the same name.
For example, this is totally fine: &name=me&name=you&name=them&name=her. On the back end, depending on which framework and language you are using, you simply get an array.
So in your form, you can use
<label> Product 1 <input name="product_name" type="text" /></label>
<label> Product 2 <input name="product_name" type="text" /></label>
...
And so on, until you've added however many forms you wish. When you submit the form, your page will automatically take care of sending them on to your backend form, where you can parse out each form programmatically.
Related
I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send.
I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below:
<p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p>
<form action="\send\" method="post">
<input type="text" name="userMessage" />
<input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" />
</form>
<script>
var btn = document.getElementById("sendButt");
btn.addEventListener("click", updateChat);
function createMenuItem(name) {
let li = document.createElement('p');
li.textContent = name;
return li;
}
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST2"))
function updateChat(){
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST3"))
}
</script>
I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading.
Thank you
You need to use django with sockets.
Take a look at this walk through.
Helped me to do the same thing a few years ago!
https://channels.readthedocs.io/en/stable/tutorial/part_2.html
I have a project in which I have to be able make a multiple input if needed. I'm really new to JavaScript and the insert method that I'm familiar with is only POST method which I parsed it from Form. My question is how do I do to use query in my script?
This is my code and the query is needed between Do...While at the bottom:
<div id="form" class="hidden">
Nama : <input type="text" name="nama"><br/>
Kuantitas : <input type="text" name="kuantitas"><br/>
Kategori : <select name="idKategori">
<?php
while ($rowKategori = mysqli_fetch_object($resultKategori)) {
echo "<option value='".$rowKategori->id."'>".$rowKategori->nama."</option>";
}
?>
</select>
<input type="hidden" name="hidden" value="bahan">
<input type="button" id="remove" value="Remove">
</div>
<form>
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
$(document).ready(function() {
var form_index = 0;
$("#add").click(function() {
form_index++;
$(this).parent().before($("#form").clone().attr("id", "form" + form_index));
$("#form" + form_index).css("display", "inline");
$("#form" + form_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + form_index);
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove" + form_index).click(function() {
$(this).closest("div").remove();
});
});
$("#insert").click(function() {
var i = 0;
do {
i++;
} while (i != 5);
});
im really bad at english , so let me explain it as simple as i can.
i wanted to make a form field with submit button, like the usual.
the difference is i wanted to make a clone button so i could add
more form field with single submit button.
the code that i write is something that i learn from another page and im not familiar with it.
i dont know how to get vallue from the cloned page, and i dont know how to handle the value itself in the script as i really noob at javascript
what i wanted to do is how do you get value from all cloned form field while i click the submit button? the method i familiran with is POST method, but i thinking about writedown all my query on the javascript since the POST method could not do the looping for all the formfield, thats why i make the loop on the javascript
and im sorry with my english, im not really good at it
Ok here you go, here is a fiddle of it.
https://jsfiddle.net/2ngjqxge/3/
HTML/PHP
<div id="form_block_wrapper" class="hidden"> <!-- added an outside wrapper -->
<div class="form_block" class="hidden">
Nama : <input type="text" name="nama[]"><br/>
Kuantitas : <input type="text" name="kuantitas[]"><br/>
Kategori : <select name="idKategori[]">
<?php while ($rowKategori = mysqli_fetch_object($resultKategori)): ?>
<option value="<?php echo $rowKategori->id; ?>">
<?php echo $rowKategori->nama; ?>
</option>
<?php endWhile; ?>
</select>
<input type="hidden" name="hidden[]" value="bahan">
<input type="button" name="remove" value="Remove">
</div>
</div> <!-- close #form_block_wrapper -->
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
Please note, I changed a number of things. Most importantly all the names of the inputs that would get submitted i added [], so nama becomes nama[] etc. Now if you were to submit this as a form, on the server side you would get arrays instead of single elements. Single elements would get overwritten by the next dynamically created "form_block" so this is what we would need to process them. The data you would expect on submission of the form would be like this ( assuming we had 3 "form_blocks" ):
$_POST['nama'] = [
0 => 'nama from first form block',
1 => 'nama from second form block',
2 => 'nama from third form block',
];
$_POST['kuantitas'] = [
0 => 'kuantitas from first form block',
1 => 'kuantitas from second form block',
2 => 'kuantitas from third form block',
];
//etc...
Next, I removed any ID's as we know ids in HTML elements must be unique, so there is no point messing with them when we are creating and destroying dynamic content. We could append an index as you originally did, but the selectors are simple enough so we don't really need to do this. And it's worth it to keep things simple, why over complicate it.
I also used the "alternative" PHP syntax for the while block. while(..): with a colon instead of while(..){ with a bracket. It just looks better to me when mixed with HTML to have the <?php endWhile; ?> insteadd of <?php } ?>. It doesn't matter much here as this is small. But after adding buches of PHP, you would have all these hanging } brackets everywhere. It's easier to keep track of the close of code blocks when they are like endIf; endWhile; etc. I also kept the HTML as HTML and not a big string that has to be echoed out, again because it looks better to me that way. It also makes dealing with the quotes " easier then having to concatenate PHP '<tag attr="'.$php.'">'.
These things you can do either way, just I'm a bit particular and a perfectionist when it comes to formatting and readability. Sort of set in my ways.
Javascript (jQuery)
(function($){
$(document).ready(function() {
//get and cache Outer HTML for .form_block
var selectHtml = $('.form_block:eq(0)')[0].outerHTML;
$("#add").click(function() {
$('#form_block_wrapper').append(selectHtml);
});
//use .on for events on dynamic content ( event delegation )
$("#form_block_wrapper").on('click', 'input[name="remove"]', function() {
$(this).closest(".form_block").remove();
});
$("#insert").click(function() {
//I have no idea what you want to do here?
//Are you trying to insert something into the page
//or Are you trying to insert the data into the DB, ie submit it to the server.
//you can serialze all the data https://api.jquery.com/serialize/
//$('#form_block_wrapper').serialize();
//you can get the selected options and get their value
var d = [];
$('select[name="idKategori[]"]').each( function(){
d.push($(this).val());
});
alert(d.join(','));
});
}); //document.ready
})(jQuery); //assign jQuery to $ - for compatibility reasons.
The first thing to do here is not clone the select but instead take a snapshot of it's html. Stored in selectHtml. There is several reasons why this is better.
if user changes the value of these fields, when we clone we have to reset all those values.
if we remove all form blocks, there is nothing to clone and we are struck on a page without our form elements, tell we refresh.
based just on the length of my code -vs- your orignal code, it should be obvious which method is simpler to handle. Simple is easy to read and maintain, do more with less.
Another thing to note, is you were attaching the remove button's event to each button as they are created. While this is ok, we can do better by using event delegation $.on to handle this element.
I still have no Idea what you want done with Insert,
do you mean insert something into the page
do you mean submit the form and insert the data somewhere.
but hopefully this helps
Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot
I am fairly new to js. Here I have a js script that adds a text box input on click for queries to a database using php based mysql. Each new added textbox has an id name with a successive number at the end for the number of added text boxes from the js button, like id_0, id_1, etc. I am wondering if its possible to run the php query for each successive textbox individually. The problem I am having is keeping track of how many new text boxes have been added to know how many iterations of the query I should run since the click number is a js variable. Is there a way to iterate a php query based on the number of js clicks, or specifically, a js variable? (or am i think of doing this in the wrong way?)
script to add input box:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var click_number = 0;
$("#btnAdd").bind("click", function () {
var div = $("<div />");
click_number++;
console.log(click_number);
div.html(GetDynamicTextBox("id"+click_number));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
click_number--;
console.log(click_number);
});
});
function GetDynamicTextBox(value0) {
return '<label>Input <textarea rows="1" name="id_'+ value0 +'"><?php echo $_POST["id_'+ value0 +'"]; ?></textarea></label> ';
}
</script>
for the php part, I turn the $_POST variable into a php variable and run a simple query to the database matching the php variable to a specific column. So far I can only do this if I know how many $_POST variables there will be.
The way I do this (it may not be the best way), is to have a hidden HTML input which contains the number of textboxes you have created. Each time you add a new text box in JS you increment the value of your hidden input.
Then you can make a loop in PHP to get each POST element.
You don't need to know how many $_POST variables there are if you write the query dynamically. Just be sure that all your POST indexes match up with column names in the table:
For example, if you have:
$_POST['name']="bob"
$_POST['age'] = "102"
You can dynamically turn that into a query..
// First, for security, we should create an array
// with column names to check against to avoid SQL injection
$tableColumns = array("name", "age", "birthday", "favorite_color");
// This will contain the data that we want to insert
$insertables = array();
// Get the data from the post variables that
// are named after columns in our table
foreach($_POST as $k->$v)
if(in_array($k, $insertables))
$insertables[$k] = $v;
// Create a a query dynamically
// I'm assuming you're using PDO since you didn't specify
$sql = $pod->prepare("INSERT INTO `table` (`".implode("`, `", array_keys($insertables))."`) VALUES (:".implode(", :", array_keys($insertables)).")");
// Execute it
$sql->execute($insertables);
Now you can send any POST data you want and if the POST key exists as a column in the table it will be inserted.
I am facing a problem in using the contact form 7 in wordpress, and need some help to all of you.
Problem:
I have radio box which have two options yes or no. if someone check the yes option then div one shoud be shown and if he clicks at no then 2nd div should be shown.
I write a code but how it will be us in contact form 7, i don't know.
here is the code.
$(document).ready(function() {
//Hide the field initially
$("#div one").hide();
$("#div two").hide();
$('[radio radio-928]').change(function()
{
if ($("[radio radio-928]").val() == "yes")
{
$("#div one").show();
}
else {
$("#div two").hide();
}
if ($("[radio radio-928]").val() == "no") {
$("#div two").show();
}
else {
$("#div one").hide();
}
});
});
This can be done in the Contact Form 7 editor box like this:
<script type="text/javascript">
function showdiv(element){
document.getElementById("div-one").style.display = element=="yes"?"block":"none";
document.getElementById("div-two").style.display = element=="no"?"block":"none";
}
</script>
<input type="radio" name="choice" value="yes" onclick="showdiv(this.value);"> Yes<br>
<input type="radio" name="choice" value="no" onclick="showdiv(this.value);"> No<br>
<div id="div-one" style="display:none;">Yes</div>
<div id="div-two" style="display:none;">No</div>
If your function works in JS console but not when saved in form, ensure it does not have blank lines.
For some reason these are turned into p tags, the editor is not really HTML aware at least on the sites I have used it on.
E.g. Capitalize first character of specific input boxes by a class.
<script language="javascript" type="text/javascript">
jQuery(function($){
// Capitalize first character as needed.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)/g, function($char) {
return $char.toUpperCase();
}));
box.setSelectionRange(stringStart, stringEnd);
});
return this;
}
$('input[type=text].capitalize').capitalize();
});
</script>
Once I remove the new line it works facepalm...
simply add you JavaScript function to your page then find the Additional Settings field at the bottom of the contact form management page and use the on_submit JavaScript action hook like so:
on_submit: "MY_JavaScript_function_Name();"
Add to your Wordpress the plugin: Insert Headers and Footers by WPBeginners
Activate the plugin and go to Settings - > Insert Headers and Footers
Add your javascript code inside script tags. When your page loads, this script will be in the head of your DOM
On Contact Form 7, add your buttons using HTML code adding the respective ID attributes mentioned on your code to control your document.
I do this all the time, specially to use jQuery.
You can copy the generated HTML of contact forms and add the javascript code. For example you have a submit form as:
[submit class:btn class:btn-lg class:btn-black "Enviar"]
If you look to the HTML code (Inspector or View Page HTML) you will have this code:
<input type="submit" value="Enviar" class="wpcf7-form-control btn-lg btn-black" disabled="">
Paste the code and add the javascript you need inside, for example:
<input type="submit" onclick="gtag('event','EnvioFormularioHome'); ga('send', 'event', { eventCategory: 'Formulario', eventAction: 'Enviado', eventLabel: 'Hernani'}) value="Enviar" class="wpcf7-form-control btn btn-lg btn-black" disabled="">
I know this is an old post but I wanted to share my discoveries in case anyone needs it later.
The OP problem is definetely the blank lines in the code, the form editor adds P elements to each new line. If you open the js console you will see the errors that points out to the code.
Also something we should pay attention, and that took me a lot of time to figure out, it that the editor removes backslashes.
I was adding some input masks validation and found this code:
v = v.replace(/\D/g, "");
becoming this after saving:
v = v.replace(/D/g, "");
So, a workaround is to declare like this:
v = v.replace(/\\D/g, "");
However, each time it is saved the backslashes would be removed, so I needed to keep its source code saved somewhere else then paste it to the editor each time.
In the end I've just added a custom html widget with all the custom js inside a script tag.
It will make the code work globally in the website but it was my way to ensure that users will not mess up the form masks and validation code.