Unable to remove form elements while using element.parentNode.removeChild(element) - javascript

I have a form that will submit to a Google search appliance, forming a query string "q".
In the form I have radio buttons and a hidden element; the radio buttons contain options for sites to select; the hidden element contains multiple sites that will allow the user to select multiple site searches.
<input type="radio" id="site_search" name="as_sitesearch" value="www.mycompany.com" checked>Current site<br />
<input type="radio" id="site_search" name="as_sitesearch" value="archive.mycompany.com">Archive site<br />
<input type="radio" id="site_search" name="as_sitesearch" value="">Both sites<br />
<input type="hidden" id="as_oqOption" name="as_oq" value="www.mycompany.com archive.mycompany.com">
This is the Javascript I wrote that will remove the radio element or the hidden element exclusively (one of them can exist in the form submittal):
// IF THE USER CHECKED "BOTH SITES", YOU WILL HAVE TO WIPE OUT THE VALUE OF as_sitesearch TO ALLOW FOR PASSING OF as_oq FOR GOOGLE ENGINE
if (form.elements['as_sitesearch'][0].value.length == 0) {
var goodbyeElement = document.getElementById('site_search');
goodbyeElement.parentNode.removeChild(goodbyeElement);
} else {
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
However, when the form is submitted, "q" winds up obtaining both radio and hidden elements no matter what radio option I click.
Not sure why this is happening as I followed the guides in the DOM tutorial sites I have read on how to remove a form element prior to submittal. Any ideas?
Thanks

Following code may help you:
(form.as_sitesearch[2].checked){
for(var k=0; k<form.as_sitesearch.length;k++){
form.as_sitesearch[k].parentNode.removeChild(form.as_sitesearch[k])
}
}
else{
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
You should call it on form submit. here form is document.form[index];

Got it! Apparently form.elements will always fail because of the grouping, so don't use it..
// IF THE USER CHECKED "BOTH SITES", YOU WILL HAVE TO WIPE OUT THE VALUE OF as_sitesearch TO ALLOW FOR PASSING OF as_oq FOR GOOGLE ENGINE
if (document.getElementById('site_search3').checked) {
for (var i = 1; i <= 3; i++) {
eval('var goodbyeElement = document.getElementById("site_search' + i + '");');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
} else {
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}

Related

How to hide certain characters within an html input list?

I have an html input list, with an associated datalist, defined as follows:
<input list="mylist" id="my-input" name="friend-name"
placeholder="Begin typing friend's name here..."
required class="form-control">
The list itself (and the associated datalist) is working fine. However, each of my entries are of the form: "String [numeric_id]"
What I am wondering is if there is any way that I can somehow hide
the [numeric_id] part before the form is submitted.
I have looked at the pattern attribute, but that seems to limit the
actual data allowed in the input, which isn't what I want - I just
want the part between square brackets [] to be hidden, but still
submitted to the form.
It would be ok to move it to another input of type=hidden as well.
Is there any possible way to do that?
#isherwood, here is my form tag:
<form action="/chat_forwarding/modal_edit_msg.php" id="fwd-form" method="POST" class="form-inline" style="display: block;">
If you're not using any framework that support binding, you should listen to input events and update a hidden input based on that.
This is a function that may give you the idea:
let realInput = document.getElementById('real-input');
let userInput = document.getElementById('user-input');
userInput.addEventListener('input', function(value) {
const inputValue = value.target.value;
realInput.value = inputValue; // update the hidden input
const userInputResult = inputValue.match(/\[[^\[]*\]/); // the regex for [numberic_id]
if (userInputResult) {
userInput.value = inputValue.substring(0, [userInputResult.index - 1]); // -1 is to remove the space between the 'string' and the '[numeric_id]'
}
});
I should have mentioned that my input is also using Awesomplete (and jQuery). For this reason, binding normal events like keyup did not work (the event would fire whenever a user typed a key). I was able to achieve the functionality I wanted with the awesomplete-selectcomplete event as follows (this will add a hidden input element with value of the id from a string of the form "String [id]"):
$("#my-input").on('awesomplete-selectcomplete',function(){
var fullStr = this.value;
//alert(fullStr);
var regex = /\[[0-9]+\]/g;
var match = regex.exec(fullStr);
//alert(match[0]);
if (match != null) // match found for [id]
{
var fullName = fullStr.substr(0,fullStr.lastIndexOf("[")-1);
var x = match[0];
var id = x.substr(1, x.lastIndexOf("]")-1);
//alert(id);
$('#fwd-form').prepend('<input type="hidden" name="h_uid" value="' + id + '">');
$('#my-input').val(fullName);
}
});

Toggling a group of checkboxes from a master checkbox

I have the following JS which is actually working and checks all my boxes if the one of the top is checked (currently works) therefore I am unable to UNCHECK them by repeating the same process (unchecking the first box is not uncheckable)
I have the following code which actually call my function each time the checkbox is unchecked or checked:
function refresh_checkbox_list(){
// document.getElementById('gdr_select_users').setAttribute("checked");
(function() {
var aa = document.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < aa.length; i++){
aa[i].checked = true;
}
})()
}
<input type="checkbox" name="gdr_select_all_users" id="gdr_select_all_users" onchange="refresh_checkbox_list()">
<input type="checkbox" name="gdr_select_users" id="gdr_select_users">
Just to say: I am a truly noob of JavaScript, I know how I would process it in PHP so it does check and uncheck, but I don't know how does "if" statements work in JS, this is my actual problem..
I was thinking about an if statement that checks if my 1st box is checked then check all others boxes, then another statement which do the exact reverse. Right?
I must admit that I have also found that JS on this website (an user which had a similar case)
Instead of using true use the checked state of #gdr_select_all_users.
Also need to exclude #gdr_select_all_users from the loop. Can use not() in the query selector or better yet apply a common class to the user checkboxes
function refresh_checkbox_list(){
// get checked state of the "check all" box
let allChecked = document.getElementById('gdr_select_all_users').checked;
(function() {
var aa = document.querySelectorAll("input[type=checkbox]:not(#gdr_select_all_users)");
for (var i = 0; i < aa.length; i++){
// set other checkboxes to same state as the "check all"
aa[i].checked = allChecked;
}
})()
}
Check all:<input type="checkbox" name="gdr_select_all_users" id="gdr_select_all_users" onchange="refresh_checkbox_list()">
<br>
User 1<input type="checkbox" name="gdr_select_users_1" >
<br>
User 2<input type="checkbox" name="gdr_select_users_2" >

Sending Checkbox and Text Input Values to URL String with Javascript

I have a list of products, each individual product has a checkbox value with the products id e.g. "321". When the products checkbox is checked (can be more than 1 selected) i require the value to be collected. Each product will also have a input text field for defining the Qty e.g "23" and i also require this Qty value to be collected. The Qty text input should only be collected if the checkbox is checked and the qty text value is greater than 1. The plan is to collect all these objects, put them in to a loop and finally turn them in to a string where i can then display the results.
So far i have managed to collect the checkbox values and put these into a string but i'm not sure how to collect the additional text Qty input values without breaking it. My understanding is that document.getElementsByTagName('input') is capable of collecting both input types as its basically looking for input tags, so i just need to work out how to collect and loop through both the checkboxes and the text inputs.
It was suggested that i use 2 if statements to accomplish this but i'm new to learning javascript so i'm not entirely sure how to go about it. I did try adding the if statement directly below the first (like you would in php) but this just seemed to break it completely so i assume that is wrong.
Here is my working code so far that collects the checkbox values and puts them in a string. If you select the checkbox and press the button the values are returned as a string. Please note nothing is currently appended to qty= because i dont know how to collect and loop the text input (this is what i need help with).
How can i collect the additional qty input value and append this number to qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
My answer has two parts: Part 1 is a fairly direct answer to your question, and Part 2 is a recommendation for a better way to do this that's maybe more robust and reliable.
Part 1 - Fairly Direct Answer
Instead of a second if to check for the text inputs, you can use a switch, like so:
var boxWasChecked = false;
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
switch(input_obj[i].type) {
case 'checkbox':
if (input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
boxWasChecked = true;
url = url + input_obj[i].value + ',qty=';
} else {
boxWasChecked = false;
}
break;
case 'text':
if (boxWasChecked) {
url = url + input_obj[i].value + '|';
boxWasChecked = false;
}
break;
}
}
Here's a fiddle showing it working that way.
Note that I added variable boxWasChecked so you know whether a Qty textbox's corresponding checkbox has been checked.
Also, I wasn't sure exactly how you wanted the final query string formatted, so I set it up as one parameter named product whose value is a pipe- and comma-separated string that you can parse to extract the values. So the url will look like this:
urlcheckout/add?product=321,qty=10|98,qty=5
That seemed better than having a bunch of parameters with the same names, although you can tweak the string building code as you see fit, obviously.
Part 2 - Recommendation for Better Way
All of that isn't a great way to do this, though, as it's highly dependent on the element positions in the DOM, so adding elements or moving them around could break things. A more robust way would be to establish a definitive link between each checkbox and its corresponding Qty textbox--for example, adding an attribute like data-product-id to each Qty textbox and setting its value to the corresponding checkbox's value.
Here's a fiddle showing that more robust way.
You'll see in there that I used getElementsByName() rather than getElementsByTagName(), using the name attributes that you had already included on the inputs:
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
First, I gather the checkboxes and use an object to keep track of which ones have been checked:
var checkedBoxes = {};
// loop through the checkboxes and find the checked ones
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
Then I gather the Qty textboxes and, using the value of each one's data-product-id attribute (which I had to add to the markup), determine if its checkbox is checked:
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
Finally, I build the url using the checkedBoxes object:
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
(Note that this way does not preserve the order of the items, though, so if your query string needs to list the items in the order in which they're displayed on the page, you'll need to use an array rather than an object.)
There are lots of ways to achieve what you're trying to do. Your original way will work, but hopefully this alternative way gives you an idea of how you might be able to achieve it more cleanly and reliably.
Check the below simplified version.
document.querySelector("#submitOrder").addEventListener('click', function(){
var checkStatus = document.querySelectorAll('#basket li'),
urls = [];
Array.prototype.forEach.call(checkStatus, function(item){
var details = item.childNodes,
urlTemplate = '/urlcheckout/add?product=',
url = urlTemplate += details[0].value + '&qty=' + details[1].value;
urls.push(url)
});
console.log(urls);
})
ul{ margin:0; padding:0}
<ul id="basket">
<li class="products"><input type="checkbox" value = "311" name="item"><input type="text"></li>
<li><input type="checkbox" value = "312" name="item"><input type="text"></li>
<li><input type="checkbox" value = "313" name="item"><input type="text"></li>
</ul>
<button id="submitOrder">Submit</button>

Multiple form fields with same 'name' attribute not posting

I'm dealing with some legacy HTML/JavaScript. Some of which I have control over, some of which is generated from a place over which I have no control.
There is a dynamically generated form with hidden fields. The form itself is generated via a Velocity template (Percussion Rhythmyx CMS) and JavaScript inserts additional hidden form fields. The end result is hidden form fields generated with the same 'name' attribute. The data is being POSTed to Java/JSP server-side code about which I know very little.
I know that form fields sharing the same 'name' attribute is valid. For some reason the POSTed data is not being recognized the back end. When I examine the POST string, the same-name-keys all contain no data.
If I manipulate the code in my dev environment such that only a single input field exists for a given name, the data IS POSTed to the back end correctly. The problem is not consistent, sometimes, it works just fine.
Is there something I can do to guarantee that the data will be POSTed? Can anyone think of a reason why it would not be?
I should really update my answer and post code here, because POST requests without
variable strings indicates the problem is on the client side.
How about this:
<script type="text/JavaScript">
function disableBlankValues()
{
var elements = document.getElementById("form1").elements;
for (var i = 0; i < elements.length; i++)
{
if (elements[i].value == "")
elements[i].disabled = true;
}
}
</script>
<form action="page.php" method="POST" onsubmit="disableBlankValues()" id="form1">
<input type="hidden" name="field1" value="This is field 1."/>
<input type="hidden" name="field1" value=""/>
</form>
EDIT
I now realize the actual problem (multiple variables with the same name should be passed to JSP as an array) and my solution is probably not what the OP is looking for, but I'm leaving it here just in case it happens to help someone else who stumbles upon this post.
you could use something like:
var form = document.getElementById('yourformid');
var elements = form.getElementsByName('repeatedName');
var count = 0;
for(var item in elements){
elements[item].name += count++;
}
this way you will get each hiddenfield with the names:
name0
name1
name2
...
I've worked out a brute-force solution. Note that I'm pretty aware this is a hack. But I'm stuck in the position of having to work around other code that I have no control over.
Basically, I've created an ONSUBMIT handler which examines the form for the repeated hidden fields and makes sure they are all populated with the correct data. This seems to guarantee that the POST string contains data regardless of how the form gets rendered and the Java back end appears to be happy with it as well.
I've tested this in the following situations:
Code generates single instances of the hidden fields (which does happen sometimes)
Code generates multiple instances of the hidden fields
Code generates no instances of the hidden fields (which should never happen, but hey...)
My 'else' condition contains a tiny bit of MooTools magic, but it's otherwise straight-forward stuff.
Maybe someone else will find this useful one day...
Thanks for the help!
<form method="post" name="loginform" id="loginform" action="/login" onsubmit="buildDeviceFP(this);">
<script type="text/javascript">
function insertFieldValues( fields, sValue )
{
if ( 'length' in fields )
{
// We got a collection of form fields
for ( var x = 0; x < fields.length; x++ ) {
fields[x].value = sValue;
}
}
else
{
// We got a single form field
fields.value = sValue;
}
}
function buildDeviceFP( oForm )
{
// Get the element collections for Device Fingerprint & Language input fields from the form.
var devicePrintElmts = oForm.elements.deviceprint;
var languageElmts = oForm.elements.language;
// 'devicePrintElmts' & 'languageElmts' *should* always exist. But just in case they don't...
if ( devicePrintElmts) {
insertFieldValues( devicePrintElmts, getFingerprint() );
} else if ( oForm.deviceprint ) {
oForm.deviceprint.value = getFingerprint();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'deviceprint', 'value':getFingerprint()} )
);
}
if ( languageElmts) {
insertFieldValues( languageElmts, getLanguage() );
} else if ( oForm.language ) {
oForm.language.value = getLanguage();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'language', 'value':getLanguage()} )
);
}
}
</script>

Javascript replace method not functioning in checkbox if/else toggle

I have a bit of Javascript I'm playing with, which is called by a number of checkboxes and will ideally perform an action (adding and removing &attributeValue=attribID to the URL cumulatively) upon the checkbox being checked/unchecked.
Here's the Javascript:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
}
else {
filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}
So what I'm doing here is attempting to on check of a checkbox add that checkbox's attributeValue to the URL, and on uncheck of a checkbox, remove that checkbox's attributeValue from the URL. I am using the filterFullURL = filterFullURL+"..." because there are multiple checkboxes and I want all their attributeValues to cumulatively be added to the URL.
All of this is working fine - the only thing that isn't working fine is the else statement action -
filterFullURL.replace("&attributeValue="+attribID, "");
Here are some example checkboxes:
<input type="checkbox" onclick="filterToggle('price_range_0_20')" name="Price_Range" value="Below_$20" id="price_range_0_20" /> Below $20
<input type="checkbox" onclick="filterToggle('price_range_20_40')" name="Price_Range" value="$20_-_$40" id="price_range_20_40" /> $20 - $40
<input type="checkbox" onclick="filterToggle('price_range_40_70')" name="Price_Range" value="$40_-_$70" id="price_range_40_70" /> $40 - $70
So to recap - I can add the attributeValues of all the checkboxes together, but I can't delete any of them. Any help here? Thanks!
Do you not need to save the output of filterFullURL.replace like filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "")?
There was also an alert missing from the if statement - not sure if that's intentional, but this should operate well for you:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
alert(filterFullURL);
}
else {
filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}

Categories

Resources