mackeemackee mackeemackee - 1 month ago 8
PHP Question

Jquery syntax, issue with none specifik ID

Im stuck with an issue of syntax in JS. Its like this, im echoing som PHP and getting diffrent ID's from DB. This is my PHP echo...

echo "<input type='text' id='form_id_" . $gr_display['id'] . "' />";


And it outputs for example

<input type='text' id='form_id_X' />


And when im clicking a button im starting this JS code, and my question is how to write this code so that im getting the ID of X?

var id=$("#form_id_").val();


HTML

echo "<form id='edit_form' method='post' action=''>";

echo "<input type='text' id='form_id_" . $gr_display['id'] . "' />";

echo "<input placeholder='New info here' type='text' id='newinfo' name='newinfo'/>";
echo "<input type='button' id='edit_btn'> Button </input>";
echo "</form>";

Answer

If you want to get the id on click (not sure it is what you want):

php: echo ""; echo "";

echo "<input placeholder='New info here' type='text' id='newinfo' name='newinfo'/>";
echo "<input type='button' id='edit_btn'> Button </input>";
echo "</form>";

js:

$("#edit_btn").on("click",function(){
    var id = $(this).prevAll(".myInput").attr("id");
    //or
    id = $(this).prevAll("[id^='form_id_']").attr("id");
    //or
    id= $(this).parent().children(".myInput").attr("id");
    //or if there is only one occurence of .myInput
    id=$(".myInput").attr("id");
    //or if there is only one occurence of [id^='form_id_']
    id = $("[id^='form_id_']").attr("id");
});
Comments