Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to detect if the current page has a form with particular name and input

I have a form which looks like this

<form action="/aa/bbcc" method="post" id="Form1" accept-charset="UTF-8">
    <input type="hidden" name="somename" value="somevalue" />
    ... other stuff
</form>

In a common $(document).ready(function() which is shared between multiple pages, I want to detect if I am in a page which has a form with the following characteristics

  • action="/aa//bbcc" & id="Form1"
  • an input with name="somename" and value="somevalue"

How do I do this?

The page has access to jquery also if that is required. Without jquery is also fine.

like image 282
user93353 Avatar asked Dec 18 '22 05:12

user93353


2 Answers

you can select the form with id and check if the node list returned is of length more than 0. Then you can check if it has an input with name 'somename' and then check if the value of that input is 'somevalue'.

   if ($('#Form1[action="/aa/bbcc"]').length > 0 && $('#Form1').has("input[name='somename']") &&
    $("#Form1 input[name='somename']").val() === "somevalue"){
       console.log('found');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/aa/bbcc" method="post" id="Form1" accept-charset="UTF-8">
<input type="hidden" name="somename" value="somevalue" />
... other stuff
</form>
like image 153
Dij Avatar answered Dec 24 '22 00:12

Dij


You can try the following

$(document).ready(function() {
  function isFormPresent() {
    return !!$("form#Form1[action='/aa/bbcc'] input[name='somename'][value='somevalue']").length
  }
  console.log(isFormPresent());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/aa/bbcc" method="post" id="Form1" accept-charset="UTF-8">
  <input type="hidden" name="somename" value="somevalue" />
</form>
like image 40
maazadeeb Avatar answered Dec 24 '22 00:12

maazadeeb