简体   繁体   中英

Change of input type by javascript don't work with Chrome but with IE, why?

This code works in IE (11.0.9600.17937) but not in Chrome (44.0.2403.157) and I can't figure out why. I'm merely a novice when it comes to JavaScript so it might be that I'm doing it all wrong, please bear with me. Would appreciate any tips to how I can get this to work.

custom.js

// Change type of a form input
function chngtype(input,form,index)
{
    document.forms[form].item(index).type = input;
}

test.php

<!DOCTYPE html>
<html lang="sv-se">
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="lib_styles/custom.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="lib_js/custom.js"></script>
</head>
<body>
<form action="test.php" method="post" name="test" role="form" id="test">
    <div class="form-group">
        <label for="alias">Test</label>
        <input type="text" name="test" class="form-control" id="test" value="Testar">
    </div>
    <button type="button" class="btn btn-default btn-sm" onClick="chngtype('submit','test',1)">Script submit</button>
    <button type="submit" class="btn btn-success">Normal submit</button>
</form>
</body>
</html>

The thing is that I want 2 submit buttons in my form but only one default. My solution is to let only one be a type="submit" and the other type="button". That way if user press enter in form it will allways go with the default submit. If user clicks the non-default submit-button i use onClick to run a JavaScript that will change the type from button to submit but it only works in IE not in Chrom (has not tested Firefox, Opera or Safari).

Can someone please tell me why and maybe point me to a solution?

The long-term fix is to find another way to do it, but if you have a lot of code that uses this method, here's something you can try to make your code cross-browser compatible:

if (typeof oForm.item == 'undefined')
{
    oForm.item=function(fieldName)
    {
        out=[];
        for (i=0; i < this.length; i++)
        {
            switch (this[i].name)
            {
                case fieldName:
                    out[out.length]=this[i];
            }
        }
        return (out.length == 1 ? out[0] : (out.length > 1 ? out : null));
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM