rock7368
rock7368

Reputation: 49

Jquery input fields

I have a form for a user to add a book, they can also attach links to online stores that sell this book using jquery since I cant determine how many the person will add, they can add a online retailer from their own input or they can select from a pre existing retailers found in database, done row by row, the problem is

Each time a new row is added, it comes from a clone.

If the person has added a online retailer in the text field as opposed to selecting a pre existing store, then select field should be disabled, or text field should be disabled if they have instead selected a pre existing retailer. This works for the first row but also affects other rows.

I only want this disabling mechanism to work row by row

i.e. If I select a retailer on the first row, the retailer text field on that row should disable, but if I select no retailer on row 2, retailer text field on row 1 should not become enabled

// Prepare vars for fields
var title = $('#title');
var description = $('#description');
var reseller_name = $('.reseller-name');
var reseller_select = $('.reseller-select');
var availability_select = $('.availability');
var url = $('.reseller-url');

// Text field to add title with book upload
$(title).keyup(function () {

    // Pattern title field must match to be valid
    var title_pattern = /^[a-zA-Z0-9\"\':?!&]{4,200}$/;

    // Text field for Book Title
    if ($(this).val() != '') {

        if (!$(this).val().match(title_pattern)) {
            // Refer to the proceeding span
            $(this).next().html('Title must consist of a minimum of 4-200 max alphabetical, numbered or the following characters \' " : ? ! &');

            // User is inserting but so far is not invalid
        } else {
            $(this).next().html('');

        }

    } else {
        $(this).next().html('');
    }
});

// ----------------------------------------------------------------------------------------------------------------- //

// Text field to add description with book upload
$(description).keyup(function () {

    // Pattern description field must match to be valid
    var desc_pattern = /^[a-zA-Z0-9\"\':?!&]{10,1500}$/;

    // Text field for Book Description
    if ($(this).val() != '') {

        if (!$(this).val().match(desc_pattern)) {
            // Refer to the proceeding span
            $(this).next().html('Description must consist of a minimum 10-1500 max alphabetical, numbered or the following characters \' " : ? ! &');

            // User is inserting but so far is not invalid
        } else {
            $(this).next().html('');

        }

    } else {
        $(this).next().html('');
    }
});

// ----------------------------------------------------------------------------------------------------------------- //

// Text field to add reseller
$(reseller_name).keyup(function () {

    // Pattern reseller name must match to be valid
    var alpha_numeric = /^[a-zA-Z0-9]+$/;

    // Each reseller_name field/index
    $('.reseller-name').each(function (i, reseller_name) {

        // Text field for Reseller Name
        if ($(this).val() != '') {

            // Disable reseller select if user is going to give a new reseller
            $(reseller_select).prop("disabled", true);

            if ($(this).val().length > 130 || !$(this).val().match(alpha_numeric)) {
                // Refer to the proceeding span
                $(this).next().html('Reseller name must consist of 130 characters or less, containing only letters or numbers');

            } else {
                $(this).next().html('');
            }

            // If field is empty
        } else {
            $(this).next().html('');
            $(reseller_select).prop("disabled", false);
        }
    });
});

// ----------------------------------------------------------------------------------------------------------------- //

// Check if user has selected any value from reseller-select other than none to avoid conflict between reseller name/select
$(reseller_select).change(function () {

    // Each reseller_select field/index
    $('.reseller-select').each(function (i, reseller_select) {

        // Disable reseller name field if anything has been chosen which is determained by the default value of none
        if ($(this).val() != 'None') {
            $(reseller_name).prop("disabled", true)
            // Else none is selected
        } else {
            $(reseller_name).prop("disabled", false)
        }
    });
});

// ----------------------------------------------------------------------------------------------------------------- //

// When submit button is clicked
$('#submit_btn').click(function () {

    var formIsValid = true;

    // Find and loop through evey span tag and see if it has text inside of it
    $('#book-form span').each(function () {

        if ($(this).html() != '') {
            formIsValid = false;
        }

    });

    // If form is valid then make sure there are values (prevents blank form submission)
    if (formIsValid) {

        $('#book-form :input').each(function () {

            if ($(this).val() == '') {
                formIsValid = false;
            }

        });

    }

    return formIsValid;

});

// Get existing fields/only need to be checked, not duplicated
var title_field = document.getElementById("title"); // Field that will contain book title
var description_field = document.getElementById("description"); // Field that will contain description

// Select allowing user to choose wheither book is currently available
var availability_select = $("<select></select>")
    .addClass("availability");

// Button to add more resellers will only get added if javascript is working
var add_reseller_btn = $(".add-reseller-btn")
    .on("click", function (e) {
    create_row();
});

// Button to submit form
var submit_btn = $("#submit_btn")
    .on("click", function (e) {
    e.preventDefault();

});

// Function append new row
function create_row() {
    var div = $(".reseller-row").last().clone(true)
    // Find field in object and set field's value to empty
    .find('.reseller-name').val("").end()
        .find('.reseller-url').val("").end();

    console.log($(div));

    // Without .last(), div gets insert after EVERY div matching class name
    $(div).insertAfter($(".reseller-row").last());
}
// Form holds everything in relation to uploading books #book-form {
    // Div hold image preview/button allowing user to upload image with book #book-image-preview {
        float: left;
        background-color: grey;
        position: relative;
        // Stretch div so book-image-preview remains centered width: 100%;
        text-align: center;
        /* On tablet and up text fields for adding a new book need to float next to book-image-preview
			so book-image-preview can't take up 100% of screem width */
        @include breakpoint(tablet) {
            width: 8.750rem;
        }
        img {
            width: 8.750rem;
            height: 10.625rem;
            display: inline-block;
        }
        // Absolute position file upload button over image input[type="file"] {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin-left: auto;
            margin-right: auto;
            height: 1.5rem;
        }
    }
    // Container holds fields for text data about book // On mobile this will have to drop below book-image-preview due to size constraints #book-fields-container {
        float: left;
        clear: both;
        @include box-sizing(border-box);
        padding: .2rem;
        background-color: yellow;
        width: 100%;
        // On tablet and up there is enough space for div containing text fields to sit next to book-image-preview @include breakpoint(tablet) {
            clear: none;
            width: 82.9%;
        }
        // Reseller-row holding fields for adding/selecting book resellers .reseller-row {
            float: left;
            clear: none;
            width: 100%;
            /* Divs within reseller row need to sit beside each other, the particular fields are part of process
				rather than separate fields with loose relation to each other */
            /* Mobile hiwever they'll have to drop due to the limited screen space */
            div {
                float: left;
                clear: both;
                // Height 100% of .reseller-row height: 100%;
                @include breakpoint(tablet) {
                    clear: none;
                }
                // First field within reseller-row - reseller name > input[type="text"] {
                    /* On mobile fields can't really be shrinked because their already squished for space as it is
						but on tablet, reseller name field needs to be shrinked so other fields can sit next to it */
                    @include breakpoint(tablet) {
                        width: 10rem;
                    }
                }
                // Select field containing existing resellers > select {
                    @include breakpoint(tablet) {
                        width: 10rem;
                    }
                }
                // Url field for user to add url with book > input[type="url"] {
                    @include breakpoint(tablet) {
                        width: 18rem;
                    }
                }
                // Button to add another reseller row > button {
                    width: 2.5rem;
                    // On tablet and up push button down so it is inline with fields @include breakpoint(tablet) {
                        margin-top: 1.2rem;
                    }
                }
            }
        }
    }
}
<!-- Form for user to add books -->
<form action="/nathan/ip_kate_blogger/www/index.php?page=admin_panel&amp;userID=5" id="book-form" method="post" enctype="multipart/form-data">
    <!-- Div holds form fields -->
    <div id="book-fields-container">
        <!-- Add or find retailer name -->
        <div class="reseller-row">
            <div>
                <label for="reseller_name">Add a retailer</label>
                <input type="text" name="reseller_name" class="reseller-name"></input>
                <!-- Span if user enters invalid retailer name -->	<span></span>

            </div>
            <div>
                <!-- Or select retailers already in database -->
                <label for="reseller_select">Existing retailers</label>
                <select name="reseller_select" class="reseller-select">
                    <option name="reseller" value="None">None</option>
                    <!-- Fill select with resellers -->
                    <!-- If select has been submitted and its value equals what came back(saved) from post -->
                    <option name="reseller" value="3">Amazon</option>
                    <!-- If select has been submitted and its value equals what came back(saved) from post -->
                    <option name="reseller" value="4">whitcolls</option>
                    <!-- If select has been submitted and its value equals what came back(saved) from post -->
                    <option name="reseller" value="5">Yahoo</option>
                </select>	<span></span>

            </div>
            <div>
                <!-- Url of retailer -->
                <label for="reseller_url">Url</label>
                <!-- Use html 5 url input type -->
                <input type="url" name="reseller_url" class="reseller-url" value=""></input>	<span></span>

            </div>
            <div>
                <button class="add-reseller-btn" type="button">Add Reseller</button>
            </div>
        </div>
        <div>
            <!-- Span to display image errors -->	<span></span>

            <input type="submit" name="submit_new_book" id="submit_btn" value="Add Book"></input>
        </div>
    </div>
</form>

Try adding news rows, going back and changing options. The rule is if retailer select is equal to none, then the text field for enter a retailer name by input should not be disabled, but if either one contains a value then the opposite field should be disabled (only on that row)

Upvotes: 1

Views: 140

Answers (1)

dm4web
dm4web

Reputation: 4652

check this solution: http://jsfiddle.net/66hjjp40/2/

changes in:

  • function create_row()
  • $('.reseller-select').change
  • $('.reseller-name').keyup

Upvotes: 2

Related Questions