I want to conduct a POST request via jQuery.
Say I have four Javascript variables: var1,var2,var3,var4 and a endpoint of URL.
How would I POST via jQuery (I would rather not be using Ajax for the sake of this example).
Put these variables into the form via hidden labels, and submit it.
If you can place a div in the html with id="myDivContent", you could add them there
var myStr = '<input name="var1" type="hidden" value="' + var1 + '" />';
myStr += '<input name="var2" type="hidden" value="' + var2 + '" />';
myStr += '<input name="var3" type="hidden" value="' + var3 + '" />';
$('#myDivContent').innerHTML = myStr;
$('form#myForm').submit();
If you just want to create a form on the fly, put these vars in there and make a POST request, then I need to update my answer.
jquery:
// var1, var2 ..., my_url must be given
$('input:hidden[name=var1]').val(var1);
$('input:hidden[name=var2]').val(var2);
...
$('#my_form').attr('action', my_url);
$('#my_form').submit();
html:
<form id="my_form">
<input type="hidden" name="var1">
<input type="hidden" name="var2">
...
</form>
No AJAX. This code actually submit your form as a normal submit action triggered by the user.
You don't need jQuery for this use-case.
I would rather create a form element(DOM) and set the variables of the form and then submit the form.
This can be done in javascript.
Here is an example.
value1 = 1234;
value2 = 5678;
value3 = 9012;
value4 = 3456;
var f = document.createElement("form")
f.method= "post"
f.action = "enpoint.url"
f.innerHTML = f.innerHTML + "<input type='text' name='var1' value='"+value1+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var2' value='"+value2+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var3' value='"+value3+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var4' value='"+value4+"'/>"
f.submit()
Related
I have some js that adds an input field for a user:
var user = "O'Conner, John"
b.innerHTML += "<input type='hidden' value='" + user + "'>";
When its inserted it looks like this:
<input type="hidden" value="O" Conner, John'>
How do I amend this so it outputs like this:
<input type="hidden" value="O'Conner, John">
I need the value to show the full name with the apostrophe. How can I get this to work?
You can escape the value first by replacing it with HTML entities.
As for ' - It can either be ’ or ‘
var user = "O'Conner, John";
user = user.replace("'", "‘");
document.getElementById("container").innerHTML += "<input type='text' value='" + user + "'>";
<div id="container"></div>
There is also another thread that already answers this question.
When you create an element with JavaScript, you can pass the value to the input without any issue. Please check the below example:
var user = "O'Conner, John"
var b = document.getElementById("b")
var input = document.createElement("input")
input.type = "text"
input.value = user;
b.appendChild(input)
<body id="b"></body>
Custom placeholders can be constructed along with text areas in Javascript like this:
var custom_placeholder = "hello";
html = '<textarea class="form-control">' + custom_placeholder + '</textarea>';
However, I cannot figure out how to do this for input tags. Below does not work. The custom placeholder appears outside the input box. So how can this be done?
html += '<input type="text"/>' + custom_placeholder;
The following syntax is not allowed as well.
html += '<input type="text">' + custom_placeholder + '</input>';
Vanilla JS
var txt = 'Hello',
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', txt);
document.body.appendChild(input);
jQuery
var txt = 'Hello';
$('body').append('<input type="text">');
$('input').attr('placeholder', txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
All you need is to concatenate the placeholderattribute within your String, like this:
html += '<input type="text" placeholder="' + custom_placeholder + '"/>';
Demo:
This is a working snippet:
var html = "";
var custom_placeholder = "A Text input";
html += '<input type="text" placeholder="' + custom_placeholder + '"/>';
document.body.innerHTML = html;
Note:
You better create the elements dynamically and append their
attributes using JavaScript.
You don't need </input> for inputs in HTML, just add a / before closing your input tag.
Also make sure the custom_placeholder variable doesn't contain special characters such as " or '.
Just use html input's placeholder attribute to set placeholder text:
let html,customPlaceholder;
html += '<input type="text" placeholder="' + customPlaceholder + '" />'
Or, if what you are looking for is actually a preset value (that the user will have to delete to enter their own input), use html's value attribute:
let html,customPlaceholder;
html += '<input type="text" value="' + customPlaceholder + '" />'
I have a form and I add divs here dynamically using append(). It is successful in creating the divs, and that divs have input fields inside. But the problem is, after serializing the the data from the form, it doesnt include the data from the dynamically created divs.
This is my createDiv function:
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
Is there a problem in creating my div? Why does serialize doesnt include the data from my created div?
Thanks in advance!
Here is where is serialize the data. When the form is submitted:
$('#explorer_form').submit(function(e){
var serializedData = $('#explorer_form').serialize();
alert(serializedData);
$.ajax({
url : url + api,
type : method,
data : serializedData,
success : function(response){
$('#response').val(JSON.stringify(response));
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
And the form:
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</submit>
</form>
And now, the alerted data is only the data from the input 'uname' only. It doesn't serialize the data from the created div.
Make sure your userQues is a form and that you do the serialize AFTER you added the inputs. Your code works, here: http://jsfiddle.net/9v3khbts/
HTML
<form id="userQues">
</form>
<button id="doSer">Serialize</button>
JS
$(document).ready(function(){
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
createDiv();
$('#doSer').click(function(){
alert($('#userQues').serialize())
})
});
<html>
<body>
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</button>
</form>
<div class="output"></div>
<script src="jquery.js"></script>
<script>
function createDiv () {
var count = 5;
for(var i=0; i<count; i++){
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
// "<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"<input id=data["+ i +"][questiona] name=data"+i+" type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>"
);
}
};
createDiv();
$('#explorer_form').submit(function(e){
e.preventDefault();
$(".output").text($("#explorer_form").serialize());
});
</script>
</body>
</html>
This works fine for me.
Don't use [] in ID or name.
Output will be -
You can use .appendTo() https://api.jquery.com/appendTo/ instead of .append()
I'm trying to add html code inside a <span id="options"></span> so I'm trying to use this:
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea('" + element.id + "')' >Add</button><br>";
}
But this is what I got,
<button type="button" onclick="updateTextArea(" textarea0')'="">Agregar</button>
My problem is with the quotes, so I later tried using createElement("button"), but now I can't add the onclick attribute.
I'm not using jQuery, so it would be nice to have a solution without it.
You need to use different quotes for the function call to updateTextArea than you do for the onclick attribute. You can't do onclick='alert('hi');', because the single quote terminates the onclick attribute.
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea(" + '"' + + element.id + '"' + ")' >Add</button><br>";
}
You should definately consider doing this at least with the proper DOM API calls. You are right to try document.createElement
To set an onclick, do something like this:
var button = document.createElement('button').
button.onclick = function(){
alert('I was clicked');
}
Can be done with escaping the quotes also:
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick=\"updateTextArea(\'" + id + "\')\" >Add</button><br>";
if you are going with second option you can use setAttribute() method.
var ele = document.createElement('button');
ele.setAttribute('onclick','method_name');
I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)