0

Please check the code bellow. I want to grab on click basis input field value. for example when click on save button it will grab its input value like "john" & "pohn" and display to console.log() from variable named CategoryName. Code bellow is failed to grab value properly. thanks in advance

Html:

<input class="form-control" id="editName" value="john"/>
<button type="button" class="btn btn-default Save" name-value="05" id-value="01">Save</button>

<input class="form-control" id="editName" value="pohn"/>
<button type="button" class="btn btn-default Save" name-value="06" id-value="02">Save</button>

jquery:

<script>

    $(document).ready(function () {

        $(".Save").on("click", function () {
            var id = $(this).attr("id-value");

            var CategoryName = $(this).attr("id").valueOf();

            console.log(CategoryName);

        });

    });

</script>
Kevin himch
  • 287
  • 3
  • 18
  • Possible duplicate of [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) – Taplar Nov 30 '17 at 17:38
  • Try using [val()](http://api.jquery.com/val/) instad of valueOf() also `var CategoryName = $(this).attr("id").valueOf();` comes empty because the button doesn't have an attribute call id... – DIEGO CARRASCAL Nov 30 '17 at 17:38

1 Answers1

1

Is this the desired output?

Note: Do not name two elements with the same ID

$(document).ready(function () {

        $(".Save").on("click", function () {
            var id = $(this).attr("id-value");

            var CategoryName = $(this).prev("input[id=editName"+id+"]").val();

            console.log(CategoryName);

        });

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control" id="editName01" value="john"/>
<button type="button" class="btn btn-default Save" name-value="05" id-value="01">Save</button>

<input class="form-control" id="editName02" value="pohn"/>
<button type="button" class="btn btn-default Save" name-value="06" id-value="02">Save</button>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54