简体   繁体   中英

JavaScript / jQuery - Recognize Type of Form Input (i.e. radio button, text input, dropdown)

I'm trying to get my JS to recognize the type of form input that is visible on the page. I'm doing a quiz, and when you hit the "next" button, it will show the next question, as long as the previous question was answered. If it was not, it should show an alert. I'm trying to get JS to recognize the type of input the question has so that it can get see if no radio button was checked, if the question was a radio button question. But so far, it's recognizing all questions as text AND radio questions. I don't know what I'm doing wrong. I've been working on this for hours.

Here is the JS Fiddle: http://bitly.com/1qy5TiX

Here is the code:

 $("button").click(function() {
 if ($("input:visible [type=text]") || $("select") ) {
    console.log("this is text or select");
 }
 if ($("input:visible :radio")) {
    console.log("this is radio");
 }
 showNext();
 }); // end button click function

I wrote you a very basic validation function since you only have one question visible at a time. You may want to look into validation libraries as well but this should get you going on the right track:

function isValid() {
    var $form = $('form:visible'),
        $input = $form.find('input'),
        $select = $form.find('select');

    var type = $input.length ? 'input' : ($select.length ? 'select' : 'error');

    if (type == 'error') {
        alert('invalid input type found');
        return false;
    }

    if ($form.find('input[type="radio"]').length) {
        return $form.find('input[type="radio"]:checked').length;    
    }

    var inputVal = $form.find(type).val();

    return inputVal !== null && inputVal.length;
}

You can check if the form is valid like so:

$("button").click(function () {
    console.log('form is valid: ' + isValid());
    if (!isValid()) {
        alert("Please enter a response.");
    } else {
        ...

FIDDLE

Also, you will probably want to replace 'form:visible' with something more concrete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM