html - Sending Checkbox and Text Input Values to URL String with Javascript -


i have list of products, each individual product has checkbox value products id e.g. "321". when products checkbox checked (can more 1 selected) require value collected. each product have input text field defining qty e.g "23" , require qty value collected. qty text input should collected if checkbox checked , qty text value greater 1. plan collect these objects, put them in loop , turn them in string can display results.

so far have managed collect checkbox values , put these string i'm not sure how collect additional text qty input values without breaking it. understanding document.getelementsbytagname('input') capable of collecting both input types looking input tags, need work out how collect , loop through both checkboxes , text inputs.

it suggested use 2 if statements accomplish i'm new learning javascript i'm not entirely sure how go it. did try adding if statement directly below first (like in php) seemed break assume wrong.

here working code far collects checkbox values , puts them in string. if select checkbox , press button values returned string. please note nothing appended qty= because dont know how collect , loop text input (this need with).

how can collect additional qty input value , append number qty=

// function loop through input tags , create  // url string checked checkboxes  function checkbox_test() {      var counter = 0, // counter checked checkboxes          = 0,       // loop variable          url = '/urlcheckout/add?product=',    // final url string          // collection of objects specified 'input' tagname          input_obj = document.getelementsbytagname('input');      // loop through collected objects      (i = 0; < input_obj.length; i++) {          // if input object checkbox , checkbox checked ...          if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {              // ... increase counter , concatenate checkbox value url string              counter++;              url = url + input_obj[i].value + '&qty=' + '|';          }      }      // display url string or message if there no checked checkboxes      if (counter > 0) {          // remove first "&" generated url string          url = url.substr(1);          // display final url string          alert(url);      }      else {          alert('there no checked checkbox');      }  }
<ul>  <li>      <form>          <input type="checkbox" id="checked-product" name="checked-product" value="311">add 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 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 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 cart</button>

my answer has 2 parts: part 1 direct answer question, , part 2 recommendation better way that's maybe more robust , reliable.

part 1 - direct answer

instead of second if check text inputs, can use switch, so:

var boxwaschecked = false;  // loop through collected objects (i = 0; < input_obj.length; i++) {      // if input object checkbox , checkbox checked ...     switch(input_obj[i].type) {        case 'checkbox':         if (input_obj[i].checked) {           // ... increase counter , concatenate checkbox value 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 fiddle showing working way.

note added variable boxwaschecked know whether qty textbox's corresponding checkbox has been checked.

also, wasn't sure how wanted final query string formatted, set 1 parameter named product value pipe- , comma-separated string can parse extract values. url this:

urlcheckout/add?product=321,qty=10|98,qty=5 

that seemed better having bunch of parameters same names, although can tweak string building code see fit, obviously.

part 2 - recommendation better way

all of isn't great way this, though, it's highly dependent on element positions in dom, adding elements or moving them around break things. more robust way establish definitive link between each checkbox , corresponding qty textbox--for example, adding attribute data-product-id each qty textbox , setting value corresponding checkbox's value.

here's fiddle showing more robust way.

you'll see in there used getelementsbyname() rather getelementsbytagname(), using name attributes had included on inputs:

checkboxes = document.getelementsbyname('checked-product'), qtyboxes = document.getelementsbyname('qty'), 

first, gather checkboxes , use object keep track of ones have been checked:

var checkedboxes = {};  // loop through checkboxes , find checked ones (i = 0; < checkboxes.length; i++) {     if (checkboxes[i].checked) {       counter++;       checkedboxes[checkboxes[i].value] = 1; // update later w/ real qty     } } 

then gather qty textboxes and, using value of each one's data-product-id attribute (which had add markup), determine if checkbox checked:

// entered qtys each checked box (i = 0; < qtyboxes.length; i++) {   pid = qtyboxes[i].getattribute('data-product-id');    if (checkedboxes.hasownproperty(pid)) {     checkedboxes[pid] = qtyboxes[i].value;   } } 

finally, build url using checkedboxes object:

// build our url object.keys(checkedboxes).foreach(function(k) {   url += [     k,     ',qty=',     checkedboxes[k],     '|'   ].join(''); }); 

(note way not preserve order of items, though, if query string needs list items in order in they're displayed on page, you'll need use array rather object.)

there lots of ways achieve you're trying do. original way work, alternative way gives idea of how might able achieve more cleanly , reliably.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -