Ron I Ron I - 3 months ago 13
Node.js Question

Getting a classname or attribute of a DOM element using post in Node and Express

I have a form that I am submitting using post. I can retrieve input values, however I also want to retrieve the class name or attribute of a div within a form.

html:

<form method='post' action='/formResult'>
<input type='text' name='someInput' />
<div class="stateAlpha" customAttr="alpha"></div> <!-- want 'alpha' -->
<button type="submit" class="btn btn-default">Submit</button>
</form>


node/express:

router.post('/formResult', function(req, res, next){
res.render('formResult', { someInput: req.body.someInput, someState: req.body.??? });
});

Answer

You'll need to intercept the submit event of the form, and put the class info into a hidden field. In pure JavaScript:

<form method='post' class='myForm' action='/formResult'>
  <input type='text' name='someInput'>
  <input type='hidden' name='state'>
  <div class="stateAlpha" customAttr="alpha"></div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
  document.querySelector('.myForm').addEventListener('submit', function(evt) {
    var alpha = evt.target.querySelector('[customAttr="alpha"]');
    var hiddenState = evt.target.querySelector('[name="state"]');
    hiddenState.value = alpha.classList.join(' ');
  });
</script>

Note that I added a class to the form, and used that to select the form; that's because you may have more than one form on the page, and you want to select the right one. Also note that inside the submit listener, I don't use document as the base of my selection, but evt.target; that's because you might have elements with customAttr='alpha' elsewhere in your document.

Once I have the div with the class you want to identify, I get the hidden input element, and set it's value property to the div's class list (remember any element can have more than one class, so classList is an array, which I just join using spaces).

If you're using jQuery, it gets a little shorter:

<form method='post' class='myForm' action='/formResult'>
  <input type='text' name='someInput'>
  <input type='hidden' name='state'>
  <div class="stateAlpha" customAttr="alpha"></div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
  $(document).ready(function() {
    $('.myForm').on('submit', function() {
      var $alpha = $(this).find('[customAttr="alpha"]');
      $(this).find('[name="state"]')
        .val($alpha.get(0).classList.join(' '));
    });
  });
</script>