Get ID of form when using onsubmit - javascript

Javascript:
function submitComment(e){
e.preventDefault();
var comment = $('#????').val(); // how do I get the ID?
// ajax
}
Comment form:
<form id="comment-form[id]" onsubmit="submitComment(event)">
<input id="comment-input[id]" type="text" placeholder="Comment...">
</form>
[id] is the variable ID of the specific form. The reason it has an ID is because I have a for loop that displays a whole list of posts, and each post has its own comment form (think Facebook).
What I want to know is how I can get the value (text) of the comment input box when they submit it based on the ID of the form that was submitted.

You can use event.target.
var comment = $('input[id^="comment-input"]',e.target).val()
This will give you input value.
e.target will give you the current form.
Then you can use [^=""] - attribute starts with selector to find the input element.
how I can get the value (text) of the comment input box based on the ID of the form that was submitted
var formID = e.target.id; //get form ID
var comment = $('#'+formID+' input[id^="comment-input"]').val()
//use $('#parent child') selector.

With your setup(HTML/javascript) you can do this with pure javascript like
function submitComment(e) {
var id = e.target.id;
id = id.match(/\[(.*?)\]/)[1];
console.log(id);
var comment = document.getElementById('comment-input['+id+']').value;
console.log(comment);
}
function submitComment(e){
var id = e.target.id;
id = id.match(/\[(.*?)\]/)[1];
console.log(id);
var comment = document.getElementById('comment-input['+id+']').value;
console.log(comment);
}
<form id="comment-form[0]" onsubmit="submitComment(event)">
<input id="comment-input[0]" type="text" placeholder="Comment...">
<input type="submit" placeholder="submit">
</form>

function submitComment(e){
e.preventDefault();
var comment = $('input[id^="comment-input"]').val();
// ajax
}
Use of jquery start-with selector can be helpful.

function submitComment(e){
e.preventDefault();
// e.currentTarget gives you the form element and then you can extract its id
var formElementId = $(e.currentTarget).attr("id");
// Then replace the form text with input which will be your comment input id
var commentElementId = formElementId.replace("form", "input");
var comment = $(commentElementId).val(); // how do I get the ID?
// ajax
}

Related

Pass form data as a parameter of a onclick function using JS DOM

I'm using DOM to generate a form like this
const my_form = document.createElement("form");
my_form.enctype = "multipart/form-data";
my_form.onsubmit = function(){return false;};
// inputs here
const div_submit = document.createElement("div");
div_submit.className = "form-group";
const submit = document.createElement("input");
submit.type = "submit";
submit.value = "Register";
submit.onclick = function(){my_function(this.form);};
div_submit.appendChild(submit);
my_form.appendChild(div_submit);
but my problem is when I set the onClick attribute of the submit input. Using this.form works when I'm writing directly on html, but when I use JS DOM it says that this.form is not defined. How can I get the data from the other inputs and pass it as a parameter of the onCLick function?
You already have the form element by my_form.
and you can get the form inputs by
my_form.elements
which will get all form inputs.
You can loop through and get it's values.
[my_form.elements].forEach(input => console.log(input.value))
For more resources.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements

Which API I need to use instead of serializeArray to get the custom attributes of fields?

I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.

How to affect the change in the original input box?

I have made an input box and i have cloned this input box to a div,let's name them ipbox1 and ipbox2, ipbox2 is the copy of ipbox1 now what i want to do is that when
i enter/change the value in either of them, the dom.value or $("#id").val() should return the updated the value. But now it's only functioning with the ipbox2.
What should i do?
fiddle
$("#ghj").click(function(){
$("#abc").val("Some text");
$("#abc").clone(true).appendTo("#pastehere");
})
$("#abc").on('change',function(){
alert();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" id = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button>
I have update you fiddle: https://jsfiddle.net/gschambial/s6td1bof/7/
var initVal = $('#abc').val();
$("#ghj").click(function(){
$("#abc").val("Some text");
$("#abc").clone(true).appendTo("#pastehere");
})
$("#abc").on('change',function(){
alert();
initVal = $(this).val();
})
$("#get").click(function(){
alert(initVal);
})
You should not append a cloned element with an id as this creates invalid markup (two html elements with the same id).
If you want to be able to read the value of either of them independently, then check out this fiddle
If not, then I must be offtrack. Please add more details about what you need to achieve :)
HTML
<input type = "text" class = "abc">This is the first box
<div id = "pastehere">
</div>This is the cloned box
<br><button type = "button" id = "ghj">
Clone
</button>
JS
var initialInput = $(".abc");
$("#ghj").click(function(){
initialInput.val("Some text");
initialInput.clone(true).appendTo("#pastehere");
})
$(".abc").on('change',function(ev){
var targetInput = $(ev.target);
alert('myValueIs:' + targetInput.val())
});

How do I retrieve data from a textbox using JavaScript?

Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;

Combine two form input values with jQuery

So I have a hidden field on my form which contains a URL (EG - http://www.domain.com?asset=)
What I need to do is on form submit extract the value from a checkbox and append it to the value in my hidden form so that the result will look something like:
http://www.domain.com?asset=123abc
Thanks in advance!
var url = 'http://www.domain.com?asset=',
jq_checkbox = $('input#my-check-box'), // suppose id of your checkbox is my-check-box
jq_hidden = $("input#my-hidden-field"), // and id of your hidden field is my-hidden-field
jq_form = $('form#my-form') // and id of your form is my-form
.submit(function(){
jq_hidden.val(url + jq_checkbox.val());
});
$("hiddenfield").val($("hiddenfield").val() + "123abc");
Simple call this function on form submir or click event you want you get your desired output here i check output by alert
<script>
function check(){
var checkbox= $("#checkbox").val();
var hidden_val= $("#url").val()+checkbox;
alert(hidden_val);
}
</script>
here
checkbox is checkbox ID
url is hideen item ID
hope it will help you

Categories