2012-06-01 57 views
4

我有一個註冊頁面的表單。該表單包含一個根據情況更改其src的圖像。 在提交表單後激活的腳本中,如果圖像具有特定的src,我希望表單調用alert,所以我需要一種檢索和比較值的方法。獲取img.src值(路徑名)

HTML:

<form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;"> 

JS:

function checkForm(f) 
    {if ([image src value] == "pictures/apic.png") 
     { 
      alert("error picture is apic"); 
      return false; 
     } 
    else 
     { 
      f.submit(); 
      return false; 
     } 
    } 

這裏是相對碼全:

<script type="text/javascript"> 
      function checkForm(f) 
      {if ([image src value] == "pictures/apic.png") 
       { 
        alert("error picture is apic"); 
        return false; 
       } 
      else 
       { 
        f.submit(); 
        return false; 
       } 
      } 
    </script> 

    <form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;"> 

    <div class="required"> 
    <label for="first_name">*First Name:</label> 
    <input type="text" name="first_name" id="first_name" class="inputText" onkeyup="checkFName(this.value);" onblur="checkFName(this.value);" maxlength="20" size="10" value="" /> 
    <img id="FName_Status" name="FName_Status" src="/pictures/bad.png" style="margin-left:5px; position:absolute;" alt="FName_Status" /> 
    </div> 

    (OTHER OBJECTS) 
    </form> 

<input type="submit" name="sub" class="inputSubmit" value="Submit &raquo;"/> 

回答

10

使用此:

if (document.getElementById('FName_Status').getAttribute('src') == "pictures/apic.png") 
+0

在哪裏指定img元素,因爲頁面上有許多元素。例如,如果

+0

'f.getElementsByTagName('img')[0]' refers to the first image element inside your 'f' form –

+0

is there any way to state a range (e.g. all elements) or do this by image id/name instead. –

1

ID標籤添加到您的圖像(如果它不已經有一個),例如:

<img src="pictures/apic.png" id="imageId" /> 

然後你就可以引用它,如下:

if (document.getElementById("imageId").src == "pictures/apic.png") 
{ 
    ... 
} 

編輯

工作示例:http://jsfiddle.net/2Wtkn/2/

+0

I tried this and it did not work –

+1

Here's a very simple fiddle demonstrating it working: http://jsfiddle.net/2Wtkn/. Perhaps if you post your entire code we can see what exactly is wrong. –

+0

I have edited my post to show all the relative code –