使用复选框隐藏和显示单选按钮

时间:2015-10-19 15:34:24

标签: javascript jquery html checkbox

基本上我想隐藏并显示单选按钮,如果选中或不选中复选框,但有一些条件。

  1. 默认情况下,即使选中复选框后隐藏了第一个单选按钮,也需要进行检查。

  2. 如果选中该复选框,则显示所有单选按钮,用户可以根据需要选择其他单选按钮。

  3. 但是,如果取消选中此复选框,请将单选按钮设置为默认选中的第一个,并隐藏所有单选按钮。
  4. 我试图修改我找到的一些解决方案,但没有成功:(

    我的HTML:

    import xbmc,xbmcaddon,xbmcgui,xbmcplugin,urllib,urllib2,os,re,sys,urlresolver,random
    from resources.libs.common_addon import Addon
    from metahandler import metahandlers
    
    addon_id        = 'plugin.video.ukturk'
    selfAddon       = xbmcaddon.Addon(id=addon_id)
    addon           = Addon(addon_id, sys.argv)
    fanart          = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id , 'fanart.jpg'))
    icon            = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
    baseurl         = 'http://www.metalkettle.co/UKTurk/Index.txt'
    adultopt        = selfAddon.getSetting('adult')
    adultpass       = selfAddon.getSetting('password')
    iconimage       = addon.queries.get('iconimage', '')
    metaset         = selfAddon.getSetting('enable_meta')
    ytapi1 ='https://www.googleapis.com/youtube/v3/search?q='
    ytapi2 ='&regionCode=US&part=snippet&hl=en_US&key=AIzaSyA7v1QOHz8Q4my5J8uGSpr0zRrntRjnMmk&type=video&maxResults=50'
    ytpl = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='
    ytpl2 = '&maxResults=50&key=AIzaSyBAdxZCHbeJwnQ7dDZQJNfcaF46MdqJ24E'
    
    def Index():
        link=open_url(baseurl)  
        match=re.compile('name="(.+?)".+?url="(.+?)".+?img="(.+?)"',re.DOTALL).findall(link)
        for name,url,iconimage in match:
            if not 'XXX' in name:
                addDir(name,url,1,iconimage,fanart)
            if 'XXX' in name:
                if adultopt == 'true':
                    if adultpass == '':
                        dialog = xbmcgui.Dialog()
                        ret = dialog.yesno('Adult Content', 'You have opted to show adult content','','Please set a password to prevent accidental access','Cancel','Lets Go')
                        if ret == 1:
                        keyb = xbmc.Keyboard('', 'Set Password')
                        keyb.doModal()
                        if (keyb.isConfirmed()):
                            passw = keyb.getText()
                            selfAddon.setSetting('password',passw)      
                        addDir(name,url,1,iconimage,fanart)
                if adultopt == 'true':
                    if adultpass <> '':
                        addDir(name,url,1,iconimage,fanart)
        addLink('UK Turk Twitter Feed','url',2,'http://www.metalkettle.co/UKTurk/thumbs/twitter.jpg',fanart)
        xbmc.executebuiltin('Container.SetViewMode(500)')
    
    def GetChans(url):
        if 'Index' in url:
            CatIndex(url)
        if 'XXX' in url:
            if adultpass <> '':
                dialog = xbmcgui.Dialog()
                ret = dialog.yesno('Adult Content', 'Please enter the password you set','to continue','','Cancel','Show me the money')
                if ret == 1:
                   try:     
                      keyb = xbmc.Keyboard('', 'Set Password')
                      keyb.doModal()
                      if (keyb.isConfirmed()):
                        passw = keyb.getText()
                      if passw == adultpass:
                    channels = GetList(url)
                    for channel in channels:
                           addLink(channel["name"],channel["url"],3,iconimage,fanart)
                   except:pass
        if 'movies' in url:
            channels = GetList(url)
            cnt = len(channels)
            for channel in channels:
                addLinkMeta(channel["name"],channel["url"],3,iconimage,cnt,isFolder=False)
            setView('movies', 'MAIN')
            if 'Index' in url:
                xbmc.executebuiltin('Container.SetViewMode(50)')
        elif 'XXX' not in url:
            burl = url
            channels = GetList(url)
            for channel in channels:
                if 'youtube.com/results?search_query=' in channel["url"]:
                    addDir(channel["name"],channel["url"],3,iconimage,fanart)
                elif 'youtube.com/playlist?list=' in channel["url"]:
                    addDir(channel["name"],channel["url"],3,iconimage,fanart)
                else:
                    if 'txt' in channel["url"]:
                        addDir(channel["name"],channel["url"],3,iconimage,fanart)
                    else:
                        addLink(channel["name"],channel["url"],3,iconimage,fanart)
            xbmc.executebuiltin('Container.SetViewMode(50)')
    
    def CatIndex(url):
        link=open_url(url)  
        match=re.compile('name="(.+?)".+?url="(.+?)".+?img="(.+?)"',re.DOTALL).findall(link)
        for name,url,iconimage in match:
            if 'youtube.com/playlist?list=' in url:
                addDir(name,url,3,iconimage,fanart)
            elif 'youtube.com/results?search_query=' in url:
                addDir(name,url,3,iconimage,fanart)
            else:
                addDir(name,url,1,iconimage,fanart)
        xbmc.executebuiltin('Container.SetViewMode(50)')
    
    def GetList(url):
        link=open_url(url)  
        matches=re.compile('^#.+?:-?[0-9]*(.*?),(.*?)\n(.*?)$',re.I+re.M+re.U+re.S).findall(link)
        li = []
        for params, name, url in matches:
            item_data = {"params": params, "name": name, "url": url}
            li.append(item_data)
        list = []
        for channel in li:
            item_data = {"name": channel["name"], "url": channel["url"]}
            matches=re.compile(' (.+?)="(.+?)"',re.I+re.M+re.U+re.S).findall(channel["params"])
            for field, value in matches:
                item_data[field.strip().lower().replace('-', '_')] = value.strip()
            list.append(item_data)
        return list
    
    def PLAYLINK(url,name):
            print url
            if 'txt' in url:
                print 'Found txt'
                GetChans(url)
            else:
                if 'youtube.com/results?search_query=' in url:
                print 'Youtube Search'
                searchterm = url.split('search_query=')[1]
                ytapi = ytapi1 + searchterm + ytapi2
                req = urllib2.Request(ytapi)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                link = link.replace('\r','').replace('\n','').replace('  ','')
                match=re.compile('"videoId": "(.+?)".+?"title": "(.+?)"',re.DOTALL).findall(link)
                print match
                for ytid,name in match:
                    url = 'https://www.youtube.com/watch?v='+ytid
                    addLink(name,url,3,iconimage,fanart)
                elif 'youtube.com/playlist?list=' in url:
                print 'Youtube Playlist'
                searchterm = url.split('playlist?list=')[1]
                ytapi = ytpl + searchterm + ytpl2
                req = urllib2.Request(ytapi)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                link = link.replace('\r','').replace('\n','').replace('  ','')
                match=re.compile('"title": "(.+?)".+?"videoId": "(.+?)"',re.DOTALL).findall(link)
                for name,ytid in match:
                    url = 'https://www.youtube.com/watch?v='+ytid
                    addLink(name,url,3,iconimage,fanart)
                elif 'dailymotion' in url:
                    print 'DailyMotion'
                    url = url.replace('video','embed/video')
                    req = urllib2.Request(url)
                    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                    response = urllib2.urlopen(req)
                    link=response.read()
                    response.close()
                    match=re.compile('mp4","url"\:"(.+?)"').findall(link)[0]
                    streamurl=match.replace('\/','/')
                    ok=True
                    liz=xbmcgui.ListItem(name, iconImage=iconimage,thumbnailImage=iconimage); liz.setInfo( type="Video", infoLabels={ "Title": name } )
                    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=streamurl,listitem=liz)
                    try:
                     xbmc.Player ().play(streamurl, liz, False)
                     return ok
                    except:
                     pass
                else:
                print 'Direct Link'
                if urlresolver.HostedMediaFile(url).valid_url():
                    streamurl = urlresolver.HostedMediaFile(url).resolve()
                else: streamurl=url 
                ok=True
                liz=xbmcgui.ListItem(name, iconImage=iconimage,thumbnailImage=iconimage); liz.setInfo( type="Video", infoLabels={ "Title": name } )
                ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=streamurl,listitem=liz)
                try:
                     xbmc.Player ().play(streamurl, liz, False)
                     return ok
                except:
                     pass
    
    def TWITTER():
        text = ''
        twit = 'https://script.google.com/macros/s/AKfycbyBcUa5TlEQudk6Y_0o0ZubnmhGL_-b7Up8kQt11xgVwz3ErTo/exec?588677963413065728'
        req = urllib2.Request(twit)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        link = link.replace('/n','')
        link = link.decode('utf-8').encode('utf-8').replace('&#39;','\'').replace('&#10;',' - ').replace('&#x2026;','')
        match=re.compile("<title>(.+?)</title>.+?<pubDate>(.+?)</pubDate>",re.DOTALL).findall(link)[1:]
        for status, dte in match:
            try:
                    status = status.decode('ascii', 'ignore')
            except:
                    status = status.decode('utf-8','ignore')
            dte = dte[:-15]
            status = status.replace('&amp;','')
            dte = '[COLOR blue][B]'+dte+'[/B][/COLOR]'
            text = text+dte+'\n'+status+'\n'+'\n'
        showText('[COLOR blue][B]@uk_turk[/B][/COLOR]', text)
    
    def showText(heading, text):
        id = 10147
        xbmc.executebuiltin('ActivateWindow(%d)' % id)
        xbmc.sleep(100)
        win = xbmcgui.Window(id)
        retry = 50
        while (retry > 0):
        try:
            xbmc.sleep(10)
            retry -= 1
            win.getControl(1).setLabel(heading)
            win.getControl(5).setText(text)
            return
        except:
            pass
    
    def open_url(url):
        url += '?%d=%d' % (random.randint(1, 10000), random.randint(1, 10000))
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        link = link.replace('\r','').replace('\t','').replace('&nbsp;','').replace('\'','')
        response.close()
        return link
    
    def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
            params=sys.argv[2]
            cleanedparams=params.replace('?','')
            if (params[len(params)-1]=='/'):
                params=params[0:len(params)-2]
            pairsofparams=cleanedparams.split('&')
            param={}
            for i in range(len(pairsofparams)):
                splitparams={}
                splitparams=pairsofparams[i].split('=')
                if (len(splitparams))==2:
                    param[splitparams[0]]=splitparams[1]
    
        return param
    
    def addDir(name,url,mode,iconimage,fanart,description=''):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': description } )
        liz.setProperty('fanart_image', fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
    
    def addLink(name,url,mode,iconimage,fanart,description=''):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': description } )
        liz.setProperty('fanart_image', fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok
    
    def addLinkMeta(name,url,mode,iconimage,itemcount,isFolder=False):
        if metaset=='true':
          if not 'COLOR' in name:
            splitName=name.partition('(')
            simplename=""
            simpleyear=""
            if len(splitName)>0:
            simplename=splitName[0]
            simpleyear=splitName[2].partition(')')
            if len(simpleyear)>0:
            simpleyear=simpleyear[0]
            mg = metahandlers.MetaData()
            meta = mg.get_meta('movie', name=simplename ,year=simpleyear)
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&site="+str(site)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=iconimage)
            liz.setInfo( type="Video", infoLabels= meta )
            contextMenuItems = []
            contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
            liz.addContextMenuItems(contextMenuItems, replaceItems=True)
            if not meta['backdrop_url'] == '': liz.setProperty('fanart_image', meta['backdrop_url'])
            else: liz.setProperty('fanart_image', fanart)
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder,totalItems=itemcount)
            return ok
        else:
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&site="+str(site)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
            liz.setInfo( type="Video", infoLabels={ "Title": name } )
            liz.setProperty('fanart_image', fanart)
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
            return ok
    
    def setView(content, viewType):
        if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
        if selfAddon.getSetting('auto-view')=='true':
        xbmc.executebuiltin("Container.SetViewMode(%s)" % selfAddon.getSetting(viewType) )
    
    params=get_params(); url=None; name=None; mode=None; site=None; iconimage=None
    try: site=urllib.unquote_plus(params["site"])
    except: pass
    try: url=urllib.unquote_plus(params["url"])
    except: pass
    try: name=urllib.unquote_plus(params["name"])
    except: pass
    try: mode=int(params["mode"])
    except: pass
    try: iconimage=urllib.unquote_plus(params["iconimage"])
    except: pass
    
    #print "Site: "+str(site); print "Mode: "+str(mode); print "URL: "+str(url); print "Name: "+str(name)
    
    if mode==None or url==None or len(url)<1: Index()
    elif mode==1:GetChans(url)
    elif mode==2:TWITTER()
    elif mode==3:PLAYLINK(url,name)
    
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
    

    非常感谢!

4 个答案:

答案 0 :(得分:0)

你在这里遇到了一些问题。首先,您需要确保关闭输入标记:

<input name="featured_ad" value="1" type="checkbox">condition</input>

<div class="buttons">
    <input type="radio" name="ad_pack_id" value="497649">value 1</input>
    <input type="radio" name="ad_pack_id" value="497648">value 2</input>
    <input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>

然后您可以通过添加checked =&#34;选中&#34;来检查html中的默认单选按钮。适当的无线电元素。

<div class="buttons">
    <input type="radio" checked="checked" name="ad_pack_id" value="497649">value 1</input>
    <input type="radio" name="ad_pack_id" value="497648">value 2</input>
    <input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>

您可以在CSS中默认隐藏单选按钮:

.buttons {
    display: none; 
}

然后,您可以使用jQuery显示它们,并根据您的条件进行选择:

$(document).ready(function(){
    $("input[name='featured_ad']").on("change", function(){
        var isChecked = $(this).prop("checked"); 
        if(isChecked){
            $(".buttons").show(); 
        } else {
            $(".buttons").hide(); 
            $("input[name='ad_pack_id'][value='497649']").prop("checked", "checked"); 
        }
    }); 
}); 

修改

这是一个小提琴:http://jsfiddle.net/8q94Lvbo/

答案 1 :(得分:0)

正如我们所讨论的,这对你有用吗?

HTML:

<input name="featured_ad" value="1" type="checkbox" onclick="resetradio(this)">condition
<div class="buttons">
    <input type="radio" name="ad_pack_id" value="497649" onclick="setcheckbox()">value 1<br>
    <input type="radio" name="ad_pack_id" value="497648" onclick="setcheckbox()">value 2<br>
    <input type="radio" name="ad_pack_id" value="497647" onclick="setcheckbox()">value 3<br>
</div>

JS:

function resetradio (checkbox) {
    var buttons = document.querySelector('.buttons');
    var radios = document.getElementsByName('ad_pack_id');
    radios[0].checked = true;
    if (checkbox.checked == true) {
        buttons.style.display = 'block';
    }
    else {
        buttons.style.display = 'none';
    }
}

function setcheckbox () {
    var checkbox = document.getElementsByName('featured_ad')[0];
    if (checkbox.checked == false) {
        checkbox.checked = true;
    }
}

CSS:

.buttons {
    display: none;
}

小提琴:http://jsfiddle.net/dgqn5fc4/1/

答案 2 :(得分:0)

执行以下操作。

$('[name="featured_ad"]').on('change', function(){
  var $first = $('[name="ad_pack_id"]').first();
  var $rest = $('[name="ad_pack_id"]').slice(1);
  if( $(this).is(':checked') ){
    $first.prop('checked',true);
    $first
      .closest('span')
      .hide();
    $rest.prop({
      'checked':false,
      'disabled':false
    });
    
  } else {
    $first
      .closest('span')
      .show();
    $first.prop('checked',true);
    $rest.prop({
      'checked':false,
      'disabled':true
    });
  }
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input name="featured_ad" value="1" type="checkbox">condition
<div class="buttons">
    <span><input type="radio" name="ad_pack_id" value="497649">value 1</span><br/>
    <span><input type="radio" name="ad_pack_id" value="497648">value 2</span><br/>
    <span><input type="radio" name="ad_pack_id" value="497647">value 3</span><br/>
</div>

答案 3 :(得分:0)

您必须在引号中将参数传递给javaScript,例如 onclick =“Show_Div('Div_1')”,而不是像 onclick =“Show_Div(Div_1)”

对于其他要求,您可以查看以下HTML

<input type="checkbox" id="check" onclick="checkFun();"/>Your CheckBox<br/>
<img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/flower-icon.png" alt="" onclick="Show_Div('Div_1')" width="100px">
    <p>
      <input id="radio1" type="radio" onclick="Show_Div('Div_1')" class="cb1" onchange="cbChange1(this)" checked="checked"/>Flower 1</p>
    <div id="Div_1" style="display: none;">
      Flower is pink.
    </div>
    <br/>
    <br/>

    <img src="http://www.clker.com/cliparts/0/d/w/v/V/p/pink-flower-md.png" alt="" onclick="Show_Div('Div_2')" width="100px">
    <p>
      <input type="radio" id="radio2" onclick="Show_Div('Div_2')" class="cb1" onchange="cbChange1(this)" disabled >Flower 2</p>
    <div id="Div_2" style="display: none;">
      Flower is orange.
</div>

您可以应用以下简单的JS和jQuery来实现目标

function checkFun(){
  console.log("click");
  var ch=$("#check");
  if(ch.is(':checked')){
    $("#radio2").attr("disabled",false);
  }else{
   $("#radio1").prop("checked", true);
    $("#radio2").prop("checked", false);
    $("#radio2").attr("disabled",true);
  }
}
function Show_Div(Div_id) {
  if(Div_id=="Div_1"){

    $("#Div_1").show();
    $("#Div_2").hide();
  }else{
    $("#Div_2").show();
    $("#Div_1").hide();
  }
}
    function cbChange1(obj) {
        var cb1 = document.getElementsByClassName("cb1");
        for (var i = 0; i < cb1.length; i++) {
            cb1[i].checked = false;
        }
        obj.checked = true;
    }